C++按map的value进行排序

来源:互联网 发布:surf算法原理 编辑:程序博客网 时间:2024/06/04 19:46

C++中,map是按key值大小排序存储。有时候,我们需要对map的value进行排序,根据value的大小顺序获得key的序列。比较简单的方法就是,重新定义一个新的map,新map的key和value正好是原来map的value和key,这样新的map就按照原来map的value值进行排序。不过这种方法,要是原来的map的value值没有重复的话,是正确的,因为map的key值是无重复的。比较正确的做法是将map转成vector,对利用vector排序。关于原理上的说明,博客(http://blog.csdn.net/acidgl8757/article/details/17416439)解释的很清楚。在此,整理了一个直接能用的,方便日后使用。

具体代码如下:

[cpp] view plain copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <iomanip>  
  4. #include <vector>  
  5. #include <map>  
  6. #include <string>  
  7. #include <algorithm>  
  8. using namespace std;  
  9.   
  10. typedef pair<string, double> PAIR;    
  11.    
  12. struct CmpByValue {    
  13.   bool operator()(const PAIR& lhs, const PAIR& rhs) {    
  14.     return lhs.second < rhs.second;    
  15.   }    
  16. };  
  17.   
  18. int _tmain(int argc, _TCHAR* argv[])  
  19. {  
  20.     //原来的map  
  21.     map<string, int> name_score_map;    
  22.     name_score_map["LiMin"] = 90;    
  23.     name_score_map["ZiLinMi"] = 79;    
  24.     name_score_map["BoB"] = 92;    
  25.     name_score_map.insert(make_pair("Bing",99));    
  26.     name_score_map.insert(make_pair("Albert",86));   
  27.   
  28.     //把map中元素转存到vector中     
  29.     vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());    
  30.   
  31.     //对vector排序  
  32.     sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());    
  33.       
  34.     //排序前  
  35.     map<string, int>::iterator iter_map;  
  36.     cout << "排序前:" << endl;  
  37.     for(iter_map = name_score_map.begin(); iter_map != name_score_map.end(); iter_map++)  
  38.         cout << left << setw(10) << iter_map->first << iter_map->second << endl;  
  39.   
  40.     cout << "排序后:" << endl;  
  41.     for (int i = 0; i != name_score_vec.size(); ++i) {    
  42.         //可在此对按value排完序之后进行操作  
  43.         cout << left << setw(10) << name_score_vec[i].first << name_score_vec[i].second << endl;    
  44.     }    
  45.     return 0;  
  46. }  
结果如图:



1
原创粉丝点击