C++中map按value排序
map默认是按key值从小到大排序的
1、对key值进行特定的排序
map容器里面有两个值一个key一个是value,map<key,value>
,其实map里面还有第三个参数,是一个类,用来对map的key进行排序的类,定义如下:
template<class _Kty,
class _Ty,
class _Pr = less<_Kty>,
class _Alloc = allocator<pair<const _Kty, _Ty> > >
class map
less<_Kty>的代码:
struct less
: public binary_function<_Ty, _Ty, bool>
{ // functor for operator<
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
那么根据上面的代码我们也可以写出一个greater类来让key按照降序排列:
注意:这里也可以不使用MyCompare 仿函数,直接用greater
#include<functional>
map<int, int, greater<int>> m;
#include <iostream>
using namespace std;
#include <map>
#include<functional>
class MyCompare {
public:
bool operator()(int v1, int v2) const
{
return v1 > v2;
}
};
void test01()
{
//默认从小到大排序
//利用仿函数实现从大到小排序
map<int, int, MyCompare> m;
//map<int, int, greater<int>> m;
m.insert(make_pair(1, 10));
m.insert(make_pair(2, 30));
m.insert(make_pair(3, 50));
m.insert(make_pair(4, 20));
m.insert(make_pair(5, 40));
for (auto it = m.begin(); it != m.end(); it++) {
cout << "key:" << it->first << " value:" << it->second << endl;
}
}
int main() {
test01();
system("pause");
return 0;
}
2、按value进行排序
将map的key和value以pair的形式装到vector中,对vector进行排序。 (下面使用unordered_map,而没有使用map)
int main()
{
unordered_map<int, int> iMap;
iMap[1] = 20;
iMap[2] = 10;
iMap[5] = 30;
iMap[4] = 0;
vector<pair<int, int>> vtMap;
for (auto it = iMap.begin(); it != iMap.end(); it++)
vtMap.push_back(make_pair(it->first, it->second));
sort(vtMap.begin(), vtMap.end(),
[](const pair<int, int> &x, const pair<int, int> &y) -> int {
return x.second < y.second;
});
for (auto it = vtMap.begin(); it != vtMap.end(); it++)
cout << it->first << ':' << it->second << '\n';
return 0;
}
这是从小到大的排序结果。
如果想要从大到小的排序,将sort函数中的第三个参数中Lambda表达式重点额函数体修改为:return x.second > y.second;
即可!