map的用法
和multimap的区别在于:
- 不能有关键字重复的元素
- 可以使用
[]
,下标为关键字,返回值为first和关键字相同的元素的second - 插入元素可能失败
应用举例:单词词频统计程序
输入大量单词,每个单词,一行,不超过20个字符,没有空格。(验证发现可以直接输入,程序会以空格或换行来检测一个单词输入的结束)按出现次数从多到少输出这些单词及其出现次数。出现次数相同的,字典序靠前的在前面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include<iostream> #include<set> #include<map> #include<string> using namespace std; struct Word { int times; string wd; }; struct Rule { bool operator () (const Word & w1, const Word & w2) const { if( w1.times != w2.times) { return w1.times > w2.times; } else return w1.wd < w2.wd; } }; int main() { string s; set< Word, Rule > st; map< string,int > mp; while(cin >> s) { ++mp[s]; } for( map<string,int>::iterator i = mp.begin(); i!= mp.end() ;i++){ Word temp; temp.wd = i->first; temp.times = i->second; st.insert(temp); } for(set<Word,Rule>::iterator i =st.begin(); i != st.end(); i++){ cout<<i->wd << ' '<<i->times <<endl; } return 0; }
|