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,192 views

35

#include <iostream>
#include <queue>
#include <vector>
#include <functional>

int main() {
    // Default: max-heap. priority_queue<T> == priority_queue<T, vector<T>, less<T>>.
    std::priority_queue<int> mx;
    for (int x : {5, 1, 4, 2, 3}) mx.push(x);
    std::cout << "max top=" << mx.top() << "\n"; // 5

    // Min-heap: pass std::greater as the comparator.
    std::priority_queue<int, std::vector<int>, std::greater<int>> mn;
    for (int x : {5, 1, 4, 2, 3}) mn.push(x);
    std::cout << "min top=" << mn.top() << "\n"; // 1

    // Drain in priority order.
    while (!mn.empty()) {
        std::cout << mn.top() << " ";
        mn.pop();
    }
    std::cout << "\n";
    return 0;
}

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).