C++ Snippet

Min-Heap via std::priority_queue

Difficulty: Medium

`std::priority_queue` is a max-heap by default. To get a min-heap you flip the comparator. This snippet shows the three common forms: a min-heap of ints with `std::greater`, a min-heap of pairs sorting by first element, and a custom comparator over a struct for things like Dijkstra. All run in O(log n) per push/pop.

Code Snippets
/

Min-Heap via std::priority_queue

Min-Heap via std::priority_queue

`std::priority_queue` is a max-heap by default. To get a min-heap you flip the comparator. This snippet shows the three common forms: a min-heap of ints with `std::greater`, a min-heap of pairs sorting by first element, and a custom comparator over a struct for things like Dijkstra. All run in O(log n) per push/pop.

C++
Medium
3 snippets
cpp-stl
priority-queue
min-heap
heap

1,191 views

35

std::priority_queue is a heap-backed adapter over a sequence container, with top returning the highest-priority element. The third template parameter is the comparator: less<T> (the default) gives a max-heap because the standard's heap routines pop the element for which the comparator returns true MOST often (the largest). Swap to greater<T> for a min-heap. Both push and pop are O(log n); top is O(1).