#include <iostream>
#include<unordered_map>
#include<set>
#include<string>
using namespace std;
//统计输入字符串中的特定单词的个数
//或者统计除特定单词之外的个数
int main()
{
unordered_map<string,int> m;
set<string> s {"!","to"};
string word;
cin>>word;
while(word != "0")
{
if(s.find(word) != s.end())//find()返回一个迭代器,仅当Word在set中的时候,返回该元素的迭代器;否则,返回尾后迭代器。
{
m[word]++;
}
cin>>word;
}
for(auto it=m.begin(); it != m.end(); ++it)
{
cout<<it->first<<" occurs "<<it->second << ((it->second >1) ? " times":" time" )<< endl;
}
return 0;
}
从map中提取元素时,会得到一个pair类型的对象。pair是一个模板类型,保存两个名为first和second的数据成员。
first保存关键字
second保存对应的值
顺便提一下:
map和unordered_map的区别:
map 按关键字 “有序” 保存元素(有序:按照字典顺序排序)
unordered_map 无序保存元素,一个无序集合。和插入顺序是相同的;