题目:map例题:单词词频统计程序
输入大量单词,每个单词一行不超过20字符,没有空格。
按出现次数从多到少输出这些单词及其出现次数,出现次数相同的字典序靠前的在前面。
核心点:使用map的关键字的不可重复性进行存储单词和出现次数,另外使用set进行排序。
代码:
#include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;
struct words { //定义键值对
string word;
int count;
};
struct rule
{//自定义排序规则
bool operator()(const words& a1, const words& a2)const {
if (a1.count != a2.count) return a1.count > a2.count;//先按出现次数多少排序
else return a1.word < a2.word;//出现次数相同按字典序排序
}
};
typedef map<string, int> MP;
int main()
{
MP mp;
string word;
set<words, rule> st;//排序的关键
while (cin >> word)
{//利用map的关键字不可重复性,进行存储关键字和关键词出现次数
pair<MP::iterator, bool> p = mp.insert(make_pair(word, 1));
if (!p.second) mp[word]++;
}
MP::iterator i;
for (i = mp.begin(); i != mp.end(); i++)
{//排序
words w;
w.word = i->first;
w.count = i->second;
st.insert(w);
}
set<words, rule>::iterator p;
for (p = st.begin(); p != st.end(); p++)
cout <<p->word << ":" << p->count << endl;
return 0;
}
实例结果:
记录于2024.11.15