【C++】map根据value排序

改变map根据key值排序策略可以重载()运算符

希望使用map根据value排序

map中元素类型是pair,第一个想到的是重载pair的<运算符

但是<utility>头文件为pair重载了<运算符

template<class _T1, class _T2>
    inline bool
    operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y)
    { return __x.first < __y.first
             || (!(__y.first < __x.first) && __x.second < __y.second); }
直接重载的话,不同的编译器可能会报错

所以还是只能写一个比较函数,将map中的pair转存到vector中,调用序列容器排序方法sort

#include "stdafx.h"
#include <map>
#include <algorithm>
#include <vector>
#include <utility>
#include <iostream>

using namespace std;

typedef pair<int, int> PAIR;

ostream& operator << (ostream& out, const PAIR& p) {
  out << p.first << "\t" << p.second;
  return out;
}

int cmp(const PAIR& left, const PAIR& right){
		return left.second < right.second;
	}

int _tmain(int argc, _TCHAR* argv[])
{
	map<int,int> test;
	test.insert(make_pair(4,3));
	test.insert(make_pair(2,5));
	test.insert(make_pair(1,3));
	test.insert(make_pair(-2,5));
	
	vector<PAIR> tmp(test.begin(),test.end());
	sort(tmp.begin(),tmp.end(),cmp);
	for(auto p=tmp.begin();p!=tmp.end();p++)
	{
		cout<<*p<<endl;
	}
	system("pause");
	return 0;

}

结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值