用map,set解决单词词频统计问题,MOOC

/单词词频统计/
#include<stdio.h>
#include
#include
#include
#include
#include
using namespace std;
struct Word{ //定义结构体,统计单词词频
int time;
string wd;
};
struct Rule{ //定义排序规则
bool operator()(const Word &w1,const Word &w2){
if(w1.time!=w2.time) //词数不等时,多的在前面
return w1.time>w2.time;
else return w1.wd<w2.wd; //词数相等时,单词字母小的在前面
}
};
int main(){
string s;
set<Word,Rule> st; //创建一个set,对Word排序
map<string,int> mp; //创建一个map,便于用下标计算词频
while(cin>>s){
if(s==“end”) break;
++mp[s]; //找到与s相同的元素的int,second++。
}
map<string,int>::iterator i; //创建map迭代器
for(i=mp.begin();i!=mp.end();i++){
Word temp;
temp.wd=i->first;
temp.time=i->second;
st.insert(temp); //添加st元素
}
set<Word,Rule>::iterator j; //创建set迭代器
for(j=st.begin();j!=st.end();j++){ //打印统计结果
cout<wd<<" "<time<<endl;
}
return 0;
}

发布了22 篇原创文章 · 获赞 1 · 访问量 1067

猜你喜欢

转载自blog.csdn.net/Doro_/article/details/94968998
今日推荐