Reputation: 232
I always wondered why STL priority queue uses max heap instead of min heap by default. Two obvious use cases that come to mind is pathfinding (Dijkstra) and building Huffman codes. Both algorithms need to pull min elements first. Since sorting (std::sort) uses ascending order by default, I wonder what was the design reasoning behind priority_queue, because I would very much prefer a min heap by default.
Upvotes: 11
Views: 3847
Reputation: 2415
In the English language, something with a larger priority should happen first. Therefore, in a priority queue, something with a higher priority should be popped first.
Basically the answer to your question is because the definition of the word priority strongly implies ordering from largest to smallest.
Just imagine a priority queue like a hospital lobby. Patients with the largest priority (urgent cases) should be a the front of the queue for treatment.
Upvotes: 0
Reputation: 127
Priority_queue is adapted from make_heap/pop_heap/push_heap/sort_heap. When you make_heap with less, the elements are sorted ascending. And the last element is treated as root element. So it is max heap. I guess there are two reasons:
Upvotes: 5
Reputation: 7157
There is a reason, but it is to do with the interconnected features of C++.
priority_queue
was designed to be an easy-to-use wrapper around make_heap
, pop_heap
and push_heap
. It makes sense for the heap functions to keep the largest value at the front, because that is what you need to be able to implement sort_heap
, which also use the heap functions.
Of course, you can always instantiate priority_queue
with greater
rather than less
to get the behaviour you want.
Upvotes: 1