您的位置:首页 > 其它

关联容器map应用-统计单词出现频率

2014-11-11 11:56 197 查看
以下程序实现:从1.txt中读入英文句子,统计每个单词出现的频率,按照字典顺序输出。

知识点:关联容器map

#include<iostream>

#include<string>

#include<fstream>

#include <algorithm>

#include<map>

using namespace std;

ifstream & open_file(ifstream& in, const string& name){

in.close();

in.clear();

in.open(name.c_str());

return in;

}

int main(){

map<string, int> word_count;

ifstream if1;

if(!open_file(if1,"1.txt")){cout<<"open
file 1.txt failed!"<<endl; return 0;}

string word;

while (if1>>word){

transform(word.begin(),word.end(),word.begin(),tolower);

++word_count[word];

}

map<string, int>::iterator map_it=word_count.begin();

while (map_it!=word_count.end()){

cout<<map_it->first<<":"<<map_it->second<<endl;

++map_it;

}

return 0;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: