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.
3 Answers
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:
- We always use less in all default STL sorting.
- push_back() or pop_back() is much more efficient than push_front() or pop_front().
2 Comments
make_heap with less, the elements are sorted ascending. And the last element is treated as root element." That's not how heaps work; see binary heap for explanation.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.
1 Comment
make_heap makes max heap rather than min heap by default? In fact, sort_heap can be implemented by either max heap or min heap.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.
std::greaterfor creating min heap viapriority_queue.