C++按map的value进行排序

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)解释的很清楚。在此,整理了一个直接能用的,方便日后使用。

具体代码如下:

 

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

typedef pair<string, double> PAIR;  
 
struct CmpByValue {  
  bool operator()(const PAIR& lhs, const PAIR& rhs) {  
    return lhs.second < rhs.second;  
  }  
};

int _tmain(int argc, _TCHAR* argv[])
{
	//原来的map
	map<string, int> name_score_map;  
	name_score_map["LiMin"] = 90;  
	name_score_map["ZiLinMi"] = 79;  
	name_score_map["BoB"] = 92;  
	name_score_map.insert(make_pair("Bing",99));  
	name_score_map.insert(make_pair("Albert",86)); 

	//把map中元素转存到vector中   
	vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());  

	//对vector排序
	sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());  
	
	//排序前
	map<string, int>::iterator iter_map;
	cout << "排序前:" << endl;
	for(iter_map = name_score_map.begin(); iter_map != name_score_map.end(); iter_map++)
		cout << left << setw(10) << iter_map->first << iter_map->second << endl;

	cout << "排序后:" << endl;
	for (int i = 0; i != name_score_vec.size(); ++i) {  
		//可在此对按value排完序之后进行操作
		cout << left << setw(10) << name_score_vec[i].first << name_score_vec[i].second << endl;  
	}  
	return 0;
}

结果如图:

 


 

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值