

//使用map
//单词计数程序
void fun1()
{
map<string, size_t> word_count; //string到size_t的空map
string word;
while(cin>>word)
++word_count[word]; //提取word的计数器并将其加1
for(const auto &w : word_count) //对map中的每个元素打印
cout<<w.first<<" occurs "<<w.second<<((w.second > 1)?" times ": " time")<<endl;
}
//使用set
//单词计数程序,忽略常见单词"the","and","or"等
void fun2()
{
map<string, size_t> word_count; //string到size_t的空map
set<string> exclude={"The","But","And","Or","An","A",
"the","but","and","or","an","a"};
string word;
while(cin>>word)
//只统计不在exclude中的单词
if(exclude.find(word) == exclude.end())
++word_count[word]; //获取并递增word的计数器
for(const auto &w : word_count) //对map中的每个元素打印
cout<<w.first<<" occurs "<<w.second<<((w.second > 1)?" times ": " time")<<endl;
}【足迹C++primer】36、使用关联容器,布布扣,bubuko.com
原文:http://blog.csdn.net/cutter_point/article/details/34103513