• 一个利用map统计一段英文文章中每个单词出现次数的小程序


    #include <fstream>
    #include <string>
    #include <map>
    using namespace std;

    int main()
    {
        map<string, int> m;
        ifstream ifs("calculate.txt");
        if(!ifs)
            return -1;
       
        string str("abcdefghigklmnopqrstuvwxyz");
        int i = 0;
        while(!ifs.eof())
        {
            char c,b;

           // 此处不可以使用输入流ifs>>c,因为输入流不读如空格。
            c = ifs.get();
            b = tolower(c);   
            if('a' <= b && b<= 'z')
            {
                str[i] = b;
                i++;
            }
            else
            {   
                string tmp;
                tmp = str.substr(0,i);
                ++m[tmp];
                i = 0;
            }   
        }
       
        string str1;
        while(cin>>str1)
        {
            cout<<str1<<"在文章中出现的次数是:";
            cout<<m[str1]<<endl;
        }
        return 0;
    };

    上述程序的map采用下标存取,若某单词不在文章中的时候,会自动添加一个键是该单词的元素,并把其值初始化为0.

    克服此缺点采用如下程序:

    #include <fstream>
    #include <string>
    #include <map>
    using namespace std;

    int main()
    {
        map<string, int> m;
        ifstream ifs("calculate.txt");
        if(!ifs)
            return -1;
       
        string str("abcdefghigklmnopqrstuvwxyz");
        int i = 0;
        while(!ifs.eof())
        {
            char c,b;
            c = ifs.get();  // 此处不可以使用输入流ifs>>c,因为输入流不读如空格。
            b = tolower(c);   
            if('a' <= b && b<= 'z')
            {
                str[i] = b;
                i++;
            }
            else
            {   
                string tmp;
                tmp = str.substr(0,i);
                if(!m.count(tmp))
                    m.insert(make_pair(tmp,1));
                else
                    m[tmp]++;
                i = 0;
            }   
        }
       
        string str1;
        while(cin>>str1)
        {
            if(m.count(str1) == 0)
                cout<<str1<<"在文章中出现的次数是0."<<endl;
            else
                cout<<str1<<"在文章中出现的次数是"<<m[str1]<<endl;
        }
        return 0;
    };

    2009/2/11 by hekex1n@126.com

  • 相关阅读:
    大爽Python入门教程 3-6 答案
    大爽Python入门教程 2-5 *拓展实践,对比与思考
    大爽Python入门教程 3-1 布尔值: True, False
    大爽Python入门教程 3-2 条件判断: if...elif..else
    企业微信获取code
    python inspect模块
    数据仓库之数据质量建设(深度好文)
    seleniumwire
    Jacoco增量代码覆盖率
    git对已经提交过的文件添加到.gitignore
  • 原文地址:https://www.cnblogs.com/kex1n/p/2286591.html
Copyright © 2020-2023  润新知