转自:http://blog.csdn.net/andyelvis/archive/2009/07/19/4361962.aspx
在STL中,map是按键来排序的,但很多时候需要按值来排序。一种方法是将map转化为vector,然后排序。
tool.h
- #ifndef TOOL_H
- #define TOOL_H
- #include <iostream>
- #include <vector>
- #include <map>
- #include <string>
- #include <algorithm>
- using namespace std;
- void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector);
- #endif
tool.cpp
- #include "tool.h"
- int cmp(const pair<string,int>& x,const pair<string,int>& y)
- {
- return x.second<y.second;
- }
- void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector)
- {
- for(map<string,int>::iterator curr=tMap.begin();curr!=tMap.end();curr++)
- {
- tVector.push_back(make_pair(curr->first,curr->second));
- }
- sort(tVector.begin(),tVector.end(),cmp);
- }
main.cpp
- #include "tool.h"
- int main()
- {
- map<string,int> tMap;
- tMap["你好"]=10;
- tMap["他好"]=5;
- tMap["我好"]=15;
- vector<pair<string,int>> tVector;
- sortMapByValue(tMap,tVector);
- for(int i=0;i<tVector.size();i++)
- {
- cout<<tVector[i].first<<": "<<tVector[i].second<<endl;
- }
- system("PAUSE");
- return 0;
- }
-