TOP N 的 STL容器 实现

来源:互联网 发布:mysql中enum 编辑:程序博客网 时间:2024/06/08 17:35

问题描述:

文件中每一行包含一个id

统计所有id中重复出现最多的N个id

这里找出来重复出现次数最多的5个id

//TOP N 实现//使用STL容器//文件中每一行是个id//求这些id中重复次数最多的五个id是什么?#include <iostream>#include <fstream>#include <string>#include <sstream>#include <map>#include <vector>#include <algorithm>using namespace std;int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y){return x.second > y.second;}void sortMapByValue(map<string, int>& m, vector< pair<std::string, int> >& v){for(map<std::string, int>::iterator curr = m.begin(); curr != m.end(); curr++){v.push_back(std::make_pair(curr->first, curr->second));}std::sort(v.begin(), v.end(), cmp);}void main(){fstream File;File.open("d://test.txt",ios::in);map<string,int> word_count;string line;while(getline(File,line)){istringstream stream(line);string word;while(stream >> word){pair<map<string,int>::iterator,bool> ret = word_count.insert(make_pair(word,1));if(!ret.second){++ret.first->second;}}}vector<pair<string,int> > v;sortMapByValue(word_count,v);for(int i=0;i<v.size();i++){if(i<5){cout<<v[i].first<<": "<<v[i].second<<endl;}}  system("pause");}