题目:在一个文本中有大量的字符串记录,统计出现次数最多的字符串及其次数。
思路:使用STL中的map可以快速的解决这个问题,map是一类关联式容器,通过RB树实现的,自动建立key-value的对应,key和value可以是任何类型。
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <vector>
#include <fstream>
#include <windows.h>
using namespace std;
int cmp(const pair<string,int>& a,const pair<string,int>& b)
{
return a.second > b.second;
}
void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector)
{
for (map<string,int>::iterator it=tMap.begin(); it!=tMap.end();it++)
{
tVector.push_back(make_pair(it->first,it->second));
}
sort(tVector.begin(),tVector.end(),cmp);
}
int main()
{
ifstream bigData("F:\\bigdata.txt");
string strIn="";
map<string,int> myMap;
vector<pair<string,int>> myVec;
while(getline(bigData,strIn))
{
if (strIn != "")
myMap[strIn]++;
}
sortMapByValue(myMap,myVec);
for (int i=0; i<10; i++)
cout<<myVec[i].second<<"\t"<<myVec[i].first<<endl;
system("pause");
return 0;
}