map 按照value排序

      大家都知道map本身內部是按照key排序的,是不能直接使用sort函數來爲map按照value排序的。

      哈!貼個自己寫的小代碼:

#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#include<vector>
#include<utility>

using namespace std;

typedef pair<string,int> PAIR;

bool cmp(const PAIR& x,const PAIR& y)
{
	return x.second<y.second;
}

int main()
{
	string s;
	map<string,int> counters;

	while(cin>>s)
		counters[s]++;

	vector<PAIR> change(counters.begin(),counters.end());

	sort(change.begin(),change.end(),cmp);

	for(int i=0;i!=change.size();i++)
		cout<<change[i].first<<"\t"<<change[i].second<<endl;

	return 0;
}


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章