In the problem of priority queue stl, where we are supposed to print the cars having minimum distance from the origin. We are passing a functor. But why the functor is having return a.distance()>b.distance();
, greater than sign for min heap? I am getting confused, that for min heap it should be <
sign.
Why do the functor is used with opposite sign?
@raghav6 A priority queue is by default a min heap, but there is no STL implementation for max heap. So to change a min heap to max heap that sign is being used there. That will return the order of elements as they are being stored in a max heap instead of a min heap.
Hope this helps.
@sgrarora3 by default it is a Max Heap, here’s the reference link https://www.geeksforgeeks.org/priority-queue-in-cpp-stl/ Even also in the video, it was mentioned that the default nature of priority queue is of max heap.
@raghav6 I apologize, I made a mistake there.
Also, > is used because the functor compares the values for new nodes in the priority queue, i.e. when functor returns true the larger nodes are swapped down the priority queue, in other words, if true is returned the larger node will be pushed down the priority queue, instead of getting swapped at the place of the root node.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.