map按值排序

来源:互联网 发布:u盘怎么装linux系统 编辑:程序博客网 时间:2024/05/10 11:52

在STL中,map是按键来排序的,但很多时候需要按值来排序。一种方法是将map转化为vector,然后排序。

 

tool.h

[cpp] view plaincopy
  1. #ifndef TOOL_H  
  2. #define TOOL_H  
  3. #include <iostream>  
  4. #include <vector>  
  5. #include <map>  
  6. #include <string>  
  7. #include <algorithm>  
  8. using namespace std;  
  9. void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector);  
  10. #endif  
 

 

tool.cpp

[cpp] view plaincopy
  1. #include "tool.h"  
  2. int cmp(const pair<string,int>& x,const pair<string,int>& y)  
  3. {  
  4.     return x.second<y.second;  
  5. }  
  6. void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector)  
  7. {  
  8.      for(map<string,int>::iterator curr=tMap.begin();curr!=tMap.end();curr++)  
  9.      {  
  10.         tVector.push_back(make_pair(curr->first,curr->second));  
  11.      }  
  12.      sort(tVector.begin(),tVector.end(),cmp);  
  13. }  
 

 

main.cpp

[cpp] view plaincopy
  1. #include "tool.h"  
  2. int main()  
  3. {  
  4.    map<string,int> tMap;  
  5.    tMap["你好"]=10;  
  6.    tMap["他好"]=5;  
  7.    tMap["我好"]=15;  
  8.    vector<pair<string,int>> tVector;  
  9.    sortMapByValue(tMap,tVector);  
  10.    for(int i=0;i<tVector.size();i++)  
  11.    {  
  12.        cout<<tVector[i].first<<": "<<tVector[i].second<<endl;  
  13.    }  
  14.    system("PAUSE");  
  15.    return 0;  
  16. }  
 

0 0
原创粉丝点击