C++学习笔记——map与set的组合使用

来源:互联网 发布:尼古丁的好处 知乎 编辑:程序博客网 时间:2024/05/17 21:32

map在单词计数程序的应用
map:关联数组;保存关键字——值对

#include<iostream>#include<string>#include<map>using namespace std;int main(){    map<string,size_t> word_count;    string word;    while(cin>>word)    {/*      istringstream a;        a.str(word);        char b;        a>>b;        cout<<b;        if(b=='\r')            {                cout<<"1";                break;             }*/        ++word_count[word];    }        for(const auto &w:word_count)        cout<<w.first<<" occurs "<<w.second<<((w.second>1?" times":" time"))<<endl;        system("pause");        return 0;}

这里有一个问题,至今未解决,就是回车不能跳出for循环,暂时用Ctrl+Z或者F6来强行跳出while

结果
这里写图片描述

w是对word_count的引用
size_t 是一种机器相关的无符号类型,它被设计的足够大以便能表示内存中任意对象的大小。在cstdef头文件中定义了size_t类型

set:关键字即值,即只保存关键字的容器

#include<iostream>#include<string>#include<map>#include<set>using namespace std;int main(){    map<string,size_t> word_count;    set<string> exclude ;    //exclude.insert{"The","But","And","Or","An","A","the","but","and","or","an","a"};    exclude.insert("The");    string word;    while(cin>>word)    {        if(exclude.find(word)==exclude.end())        ++word_count[word];    }        for(const auto &w:word_count)        cout<<w.first<<" occurs "<<w.second<<((w.second>1?" times":" time"))<<endl;        system("pause");        return 0;}

这里写图片描述
此外还应补充的一点是 map 与 set 的关键字都是不能改变的

1 0
原创粉丝点击