关联容器与顺序容器的本质差别在于:一个是按键存储和访问元素,另一个是按元素在容器中的位置顺序存储和读取元素。
在map容器中,如果下标表示的键不存在则创建新元素,这一特性对于统计单词的频率非常简单!
#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
int main()
{
map<string,int> word_count; //word_count用来记录单词出现的次数
vector<string> words;
cout<<"Enter some words:"<<endl;
string word;
while(cin>>word)
{
//如果该键不存在,则将它放入容其中
if( find(words.begin(),words.end(),word)==words.end() )
words.push_back(word);
++word_count[word];
}
cout<<endl<<"The word are:"<<endl;
for(vector<string>::iterator it=words.begin();it!=words.end();++it)
cout<<*it<<": "<<word_count[*it]<<endl;
return 0;
}
Enter some words:
hot tokyo bath angel lip lip hot bath
The word are:
hot: 2
tokyo: 1
bath: 2
angel: 1
lip: 2