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 的关键字都是不能改变的