简体   繁体   English

重载运算符时priority_queue的顺序?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM