std::priority_queue<T> · C++

push / emplace

Adds an element: c.push_back(value) followed by std::push_heap.

void push(const value_type& value); template<class... Args> void emplace(Args&&... args);

Complexity

Worst caseO(log n) comparisons, plus the container's push_back (amortized O(1) for vector)
Extra spaceO(1) amortized

push_heap sifts the new last element up: at most log₂ n comparisons.

Tested example

std::priority_queue<int> heap;  // std::less: the LARGEST element is on top (max-heap)
heap.push(5);
heap.push(1);
heap.push(3);
assert(heap.top() == 5);
std::priority_queue<int, std::vector<int>, std::greater<>> min_heap;  // smallest on top
min_heap.push(5);
min_heap.push(1);
assert(min_heap.top() == 1);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/priority_queue_examples.cpp

Parameters

value / args
The element or its constructor arguments.

Behaviour

Returns
Nothing.
Errors and preconditions
Exceptions from the container or the comparison.
Changes
size() increases by 1.
Memory and invalidation
May reallocate the vector.