412-C++中map自定义key和value排序

本文介绍了如何在C++中对map按value值进行排序。首先,通过自定义比较函数或者使用greater仿函数可以实现map的key按降序排列。其次,若要按value排序,可以将map的元素转换为vector<pair<int, int>>,然后使用sort函数配合Lambda表达式对vector进行排序,从而达到按value从小到大或从大到小排序的效果。示例代码详细展示了这两种方法的实现。
摘要由CSDN通过智能技术生成

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; 即可!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liufeng2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值