Can anyone please help me, i have this doubt since a long time and i didn’t find anything helpful on internet?
Can anyone please explain how comparators(or operators) work with priority_queues?
For creating min heap, we use following struct compare
struct compare{
bool operator()(item a, item b){
return a > b;
}
};
The C++ reference has this description of compare :
A binary predicate that takes two elements (of type T) as arguments and returns a bool
.
The expression comp(a,b)
, where comp is an object of this type and a and b are elements in the container, shall return true
if a is considered to go before b in the strict weak ordering the function defines.
The priority_queue uses this function to maintain the elements sorted in a way that preserves heap properties (i.e., that the element popped is the last according to this strict weak ordering ).
This can be a function pointer or a function object, and defaults to less<T>
, which returns the same as applying the less-than operator (a<b
).
Now as per this our operator returns true when a > b and that will mean that a will go before b in our priority queue. So doesn’t our priority queue became max heap(since a>b) instead of min heap?
But it works like a min heap, i don’t know where am i wrong?
Thanks in advance.
@cubefreak777 @vijju123 @ssrivastava990