STL map 按值排序

  1. //在STL中,map是按键来排序的,但很多时候需要按值来排序。一种方法是将map转化为vector,然后排序。
  2. #include <iostream>  
  3. #include <vector>  
  4. #include <map>  
  5. #include <string>  
  6. #include <algorithm>  
  7. using namespace std;  
  8. void sortMapByValue(map<string,int>& tMap,vector<pair<string,int> >& tVector);  
  9. int cmp(const pair<string,int>& x,const pair<string,int>& y)  
  10. {  
  11.     return x.second<y.second;  
  12. }  
  13. void sortMapByValue(map<string,int>& tMap,vector<pair<string,int> >& tVector)  
  14. {  
  15.       for(map<string,int>::iterator curr=tMap.begin();curr!=tMap.end();curr++)  
  16.       {  
  17.          tVector.push_back(make_pair(curr->first,curr->second));  
  18.       }  
  19.       sort(tVector.begin(),tVector.end(),cmp);  
  20. }  
  21. int main()  
  22. {  
  23.     map<string,int> tMap;  
  24.     tMap["你好"]=10;  
  25.     tMap["他好"]=5;  
  26.     tMap["我好"]=15;  
  27.     vector<pair<string,int> > tVector;  
  28.     sortMapByValue(tMap,tVector);  
  29.     for(int i=0;i<tVector.size();i++)  
  30.     {  
  31.         cout<<tVector[i].first<<": "<<tVector[i].second<<endl;  
  32.     }  
  33.     return 0;  
  34.  }  

posted on 2011-07-31 09:28  原来...  阅读(4636)  评论(0编辑  收藏  举报

导航