Back to The Haunt
The craft3 min read

priority_queue is a max-heap. Flip it.

std::priority_queue puts the largest element on top by default, because its comparator is std::less and the queue serves whatever compares greatest. To make it a min-heap, give it std::greater<> as the third template argument. That means you also have to name the container, which is almost always std::vector.

Three min-heaps

#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
int main() {
    std::priority_queue<int> maxFirst;                                   // default: max-heap
    std::priority_queue<int, std::vector<int>, std::greater<>> minFirst; // min-heap
    for (int x : {5, 2, 8, 4}) {
        maxFirst.push(x);
        minFirst.push(x);
    }
    std::cout << maxFirst.top() << ' ' << minFirst.top() << '\n';       // 8 2
    // Pairs compare by first, then second: (distance, node) for Dijkstra.
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> frontier;
    frontier.emplace(7, 1);
    frontier.emplace(3, 4);
    frontier.emplace(3, 2);
    while (!frontier.empty()) {
        auto [dist, node] = frontier.top();
        frontier.pop();
        std::cout << dist << ':' << node << ' ';
    }
    std::cout << '\n';                                                   // 3:2 3:4 7:1
    // A lambda: return true when a should come out AFTER b.
    struct Task { std::string name; int deadline; };
    auto later = [](const Task& a, const Task& b) { return a.deadline > b.deadline; };
    std::priority_queue<Task, std::vector<Task>, decltype(later)> tasks(later);
    tasks.push({"ship", 5});
    tasks.push({"test", 2});
    tasks.push({"write", 1});
    while (!tasks.empty()) {
        std::cout << tasks.top().name << ' ';
        tasks.pop();
    }
    std::cout << '\n';                                                   // write test ship
}

Build it with g++ -std=c++20 -Wall -Wextra pq.cpp or the Clang equivalent. push and pop take O(log n) time, and top is O(1).

Read the comparator backwards

The comparator answers "should a sit below b?", so it names the item that comes out later. With std::less, smaller items sit lower and the largest comes out first. With std::greater, or a lambda that returns a.deadline > b.deadline, the smallest comes out first. If your heap comes out in the wrong order, flip the comparison.

std::greater<> with empty angle brackets works for any type that has >, including pairs and tuples, which compare by their first field and then the next.

Traps

  • `pop()` returns nothing. Read top() first, then call pop().
  • `top()` on an empty queue is undefined behaviour. It may print garbage instead of crashing. Check empty() first.
  • The negation trick overflows. Pushing -x into the default max-heap works for most ints, but -INT_MIN overflows. std::greater<> has no such edge.
  • Ties come out in no promised order. If equal priorities must come out first in, first out, add an arrival counter as the second field of a tuple.
  • A comparator must be strict. Use >, not >=. A comparator that says an item comes before itself breaks the heap.

Chapter 10 of our free C++ for DSA book writes a min-heap in a vector with sift-up and sift-down before it uses std::priority_queue, and it shows the tie-breaking counter in a full program. Books in four more languages are on the DSA hub.

That’s it. Come back soon; the ghost keeps writing.Follow by RSS

Read next.