使用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