C++ · Priority queue · adapter

std::priority_queue<T>

A container adapter that keeps a vector in heap order with std::push_heap/pop_heap: O(log n) push and pop, O(1) top. A max-heap by default.

#include <queue>
template<class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>> class priority_queue;

C++23

Operations

OperationTimeWorst caseChanges the collection
push / emplaceO(log n) comparisons, plus the container's push_back (amortized O(1) for vector)O(log n) comparisons, plus the container's push_back (amortized O(1) for vector)Yes
popO(log n) (at most 2 log₂ n comparisons)O(log n) (at most 2 log₂ n comparisons)Yes
topO(1)O(1)No
Construct from a rangeO(n) (make_heap: at most 3n comparisons)O(n) (make_heap: at most 3n comparisons)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
A protected Container c (std::vector by default) maintained with the heap algorithms of <algorithm>.
Ordering
top() is the largest element under Compare (std::less gives a max-heap; std::greater<> a min-heap).
Duplicates
Allowed.
Mutability
Only top, push, emplace, pop are exposed; no iteration, no access to other elements, no decrease-key.
Memory and ownership
Whatever the underlying container uses.
Equality and comparison
Compare must be a strict weak ordering.

An adapter, not a container: the same pattern as std::queue and std::stack.

Pitfalls

  • It is a max-heap by default, unlike C#, Java and Python, whose priority queues are min-first.
  • pop() returns nothing; read top() first. Both are undefined behaviour on an empty queue.
  • You cannot iterate it; copy and pop, or use the heap algorithms on a vector directly.

Alternatives

  • std::make_heap / push_heap / pop_heap on a std::vector you control
  • std::set or std::multiset for ordered iteration and erase of arbitrary elements

In other languages

References