Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparators in sort function and priority queue c++

In C++ Sort function, the third optional parameter is a comparator used to sort the objects. If we pass in less as the comparator, we will get objects in increasing order. (if the comparator is evaluated to be true, the positions won't be changed, otherwise elements will be swaped!) Is my understanding correct?

Following the same fashion, if we pass a less comparator to priority queue, we should get a min-heap,(if the underlying data structure is chosen to be vector, objects are sorted in increasing order. If we call top(), the first element of vector will be returned, which is the smallest number. Therefore, I think it is a min heap) why do we get a max heap?

like image 928
Zixin Liu Avatar asked Aug 14 '26 07:08

Zixin Liu


1 Answers

According to this online documentation, the C++ library class std::priority_queue returns the largest element first in the sense that the comparator orders smaller elements before larger elements. From above link:

Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. That is, the front of the queue contains the "last" element according to the weak ordering imposed by Compare.

Thus std::priority_queue<T,std::less<T>> makes a max-heap and prioritizes larger elements.

like image 110
Walter Avatar answered Aug 16 '26 19:08

Walter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!