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
std::lessto allow new elements to "sink" down in the heap. This, however, brings the largest element to the top of the heap. In order to get the smallest element to rise to the top of the heap, you have to usestd::greater.std::less and<should be the default for all comparitors in the Standard Library. I am no expert, but I believe that is still true today. Whenstd::priority_queuewas designed, it made sense that the element with the highest priority should be first out of the queue. So,std::priority_queuewas crafted so that it could usestd::lessto output the "biggest" element. To get the smallest, you have to invert the comparison.