1. 程式人生 > >海量資料中,找出出現次數TOPK的記錄

海量資料中,找出出現次數TOPK的記錄

題目:在一個文字中有大量的字串記錄,統計出現次數最多的字串及其次數。

思路:使用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;
}