改变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;
}
结果: