Why does priority_queue use greater<> for ascending order?

111 views Asked by At

Why does priority_queue use greater<> for ascending order?

Since sort() method in c++ STL uses greater<>() as a third parameter to make descending order it's confusing for me that priority_queue uses greater<> for the opposite order.

Why and How does it work this way? I don't understand how the same greater structure behaves different depending on where it is used.

sort<temp.begin(),temp.end(),greater<>()>; // -> descending order

priority_queue<int,vector<int>,greater<int>>; // -> ascending order
1

There are 1 answers

0
Nicol Bolas On

You're thinking incorrectly about the meaning of a priority queue. When you remove an item from a priority queue, you are removing the highest priority item. Yes, a priority queue uses an ordering functor, but that ordering functor only says which item has the higher priority.

You should not think of the ordering functor as "sorting"; it simply compares the relative priority of the elements.

the same greater structure

They don't have "the same greater structure". sort is an algorithm; it operates on a sequence of elements. priority_queue is a container-adapter; it is a sequence of elements. sort does a thing once and then it's over. priority_queue is the thing.