マップでは、問題を解決するために単語の頻度統計を設定し、MOOC

/ Wordのワード頻度統計 /
書式#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