您的位置:首页 > 其它

单词词频统计程序(map set 应用)

2017-08-24 10:01 309 查看
题目:

输入大量单词,每词一行,不超过20字符,没有空格。按出现次数从多到少输出这些单词及其出现次数。出现次数相同的,按字典序输出。

实现:

#include<iostream>
#include<string>
#include<map>
#include<set>
using namespace std;

struct Word{
int times;
string wd;
};
struct Rule{//自定义的比较
bool operator()(const Word &w1,const Word &w2){
if(w1.times != w2.times)
return w1.times > w2.times;
else{
return w1.wd < w2.wd;
}
}
};

int main()
{
//freopen("C:\\Users\\zhangwei\\Desktop\\input.txt","r",stdin);
string s;
set<Word,Rule> st;
map<string, int> mp;
while(cin >> s)
++mp[s];// mp[s] 表示的就是对应的s的second值
for(map<string, int>::iterator i = mp.begin(); i != mp.end(); i++ ){
Word tmp;
tmp.wd = i->first;
tmp.times = i->second;
st.insert(tmp);//插入过程 自动排序了
}
for(set<Word,Rule>::iterator i = st.begin(); i != st.end(); i++ ){
cout <<i->wd << " " << i->times<<endl;
}

return 0;
}


这里用到的STL 中的 set map  string
(1):首先是 set<Word,Rule> 表示 元素类型为Word 并且按照规则 Rule进行排序
(2):然后map<string,int>  mp, mp的第一个元素为string(关键字),mp的第二个元素为int类型。
            也就类似有两个结构变量 分别为 first, second(可以用迭代器直接调用)
           其中mp[string] 表示的就是 second的值  并且 每个string关键字初始为0 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: