priority_queue元素为指针时,重载运算符失效

使用priority_queue构造最大最小堆时,发现priority_queue中元素为指针时,std::greater/std::less函数并不能调用到自定义数据的重载运算符,排序结果是根据指针地址大小计算的,从而导致最大最小堆失效。

#include <iostream>
#include <vector>
#include <queue>

void log(const char* str)
{
	std::cout << str;
}

void log(const int v)
{
	std::cout << "" << +v << " ";
}

struct Stuent
{
	int score = 0;
	bool operator >(const Stuent& right) const
	{
		return this->score > right.score;
	}
};

int main()
{
	//构造最小堆
	std::priority_queue<Stuent*, std::vector<Stuent*>, std::greater<Stuent*>> minHeap;
	
	for (auto i : { 1,3,5,9,8,6,2,7,4,0 })
	{
		Stuent* stu=new Stuent;
		stu->score = i * 10;
		minHeap.push(stu);
	}

	log("最小堆:\n");
	while (!minHeap.empty())
	{
		auto stu = minHeap.top();
		log(stu->score);
		printf("%lld\n", (uint64_t)stu);
		minHeap.pop();
		delete stu;
		stu = nullptr;
	}
	getchar();
	return 0;
}

 失效的最小堆,可以看到是按指针地址排序的。

如何解决呢?

实现比较函数:

constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const {
        return _Left > _Right;
    }

测试代码如下: 

#include <iostream>
#include <vector>
#include <queue>

void log(const char* str)
{
	std::cout << str;
}

void log(const int v)
{
	std::cout << "" << +v << " ";
}

struct Stuent
{
	int score = 0;
	bool operator >(const Stuent& right) const
	{
		return this->score > right.score;
	}
};

struct StuentCmp
{
	bool operator()(const Stuent* left, const Stuent* right) const
	{
		return left->score > right->score;
	}
};

int main()
{
	//构造最小堆
	std::priority_queue<Stuent*, std::vector<Stuent*>, StuentCmp> minHeap;
	
	for (auto i : { 1,3,5,9,8,6,2,7,4,0 })
	{
		Stuent* stu=new Stuent;
		stu->score = i * 10;
		minHeap.push(stu);
	}

	log("最小堆:\n");
	while (!minHeap.empty())
	{
		auto stu = minHeap.top();
		log(stu->score);
		minHeap.pop();
		delete stu;
		stu = nullptr;
	}
	getchar();
	return 0;
}

 参考资料:https://en.cppreference.com/w/cpp/utility/functional/greater

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值