[英]The order of priority_queue when overloading the operator?
Hi I am trying to understand how the comparator works for priority_queue in c++. It confuses me for a long time.嗨,我想了解比较器如何在 c++ 中为 priority_queue 工作。这让我很困惑。
Let's say we have this struct:假设我们有这个结构:
struct compare{
public:
bool operator()(Node& a,Node& b) // overloading both operators
{
return a.w < b.w: // if you want increasing order;(i.e increasing for minPQ)
return a.w > b.w // if you want reverse of default order;(i.e decreasing for minPQ)
}
};
And we can create the pq in this way:我们可以这样创建 pq:
priority_queue<Node,vector<Node>,compare> pq;
I want to know why "operator<" is minq, ie pq.top()
is the minimum?我想知道为什么“operator<”是minq,即
pq.top()
是最小值? while "operator>" is maxq?而“operator>”是maxq?
If the ordering function returns true, then the first object will come before the second object.如果排序 function 返回真,那么第一个 object 将在第二个 object 之前出现。
So if you have所以如果你有
return a.w < b.w;
and it's true then a
will come before b
.确实如此
a
会在b
之前出现。
Same with与
return a.w > b.w;
If it's true then a
will come before b
.如果为真,则
a
将出现在b
之前。
This is well documented .这是有据可查的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.