Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::priority_queue use max heap instead of min heap?

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.

like image 903
mar Avatar asked Aug 31 '14 09:08

mar


People also ask

Is Priority Queue a max heap by default?

Note: By default, C++ creates a max-heap for the priority queue.

Why do we use greater INT for min heap?

The C++ heap functions make_heap , push_heap , and pop_heap operate on a max heap, meaning the top element is the maximum when using the default comparator. So, to create a min-heap, you need to use greater<T> instead of less<T> .

How do I declare a priority queue as min heap?

priority_queue supports a constructor that requires two extra arguments to make it min-heap. priority_queue <Type, vector<Type>, ComparisonType > min_heap; `The third parameter, 'Comparison Type' can either be a function or factor (aka function object) that must have bool as return-type and must have 2 arguments.

How do you initialize a min heap?

To build a min heap we:Create a new child node at the end of the heap (last level). Add the new key to that node (append it to the array). Move the child up until you reach the root node and the heap property is satisfied.


1 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:

  1. We always use less in all default STL sorting.
  2. push_back() or pop_back() is much more efficient than push_front() or pop_front().
like image 112
Dengzhi Zhang Avatar answered Oct 05 '22 03:10

Dengzhi Zhang