自定义std::map的排序

这篇博客介绍了如何自定义std::map的排序规则,使其按照key的值而非默认的红黑树顺序进行排序。通过创建自定义比较类MyCompare并传入map的构造函数,实现了根据MyType对象的value属性进行升序排序。示例代码展示了如何创建和使用这个自定义排序的map。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::map的内部排序是按照红黑树进行的,所以,查询时间复杂度为O(log2n).
参考博客:https://www.cnblogs.com/stay-alive/p/8215400.html

#include “pch.h”
#include
#include
#include <string.h>
#include
#include
using namespace std;

class MyType
{
public:
MyType(int vale)
{
value = vale;
}

int GetValue()const
{
    return value;
}

private:
int value;
};

class MyCompare
{
public:
bool operator()(const MyType& lhs, const MyType& rhs)const
{
return lhs.GetValue() > rhs.GetValue();
}
};

void Test()
{
std::map<MyType, std::string, MyCompare> mapValueToName;
mapValueToName[MyType(3)] = “three”;
mapValueToName[MyType(0)] = “zero”;
mapValueToName[MyType(2)] = “two”;
mapValueToName[MyType(6)] = “six”;
mapValueToName[MyType(4)] = “four”;
mapValueToName[MyType(5)] = “five”;

for (std::map<MyType, std::string, MyCompare>::iterator iter = mapValueToName.begin(); iter != mapValueToName.end(); iter++)
{
    cout << "value: " << iter->first.GetValue() << "    name: " << iter->second.c_str() << endl;
}

}

int main()
{
Test();
system(“pause”);
return 0;
}

结果如下图所示:
在这里插入图片描述
以上方式为std::map按“key”排序,接下来介绍std::map按值排序的方法!!

	struct funCmpByValue {
		bool operator()(const PAIR& left, const PAIR& right) {
			return left.second > right.second;
		}

	//直接用sort对MAP排序是做不到的.可以把map装进pair里,然后将pair放入vector,自定义sort实现排序
	std::vector<std::pair<std::string, double>> nameScoreArray(nameScoreMap.begin(), nameScoreMap.end());
	sort(nameScoreArray.begin(), nameScoreArray.end(), funCmpByValue());
	for (size_t i=0; i<nameScoreArray.size(); i++)
	{
		PAIR _pair = nameScoreArray[i];
		std::cout << _pair.first << " : " << _pair.second << std::endl;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值