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

来源:互联网 发布:hifi播放器 知乎 编辑:程序博客网 时间:2024/05/22 04:30

以下程序实现:从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;
}

0 0
原创粉丝点击