std::priority_queue<T> · C++

Construct from a range

Builds the heap from many elements at once with std::make_heap.

template<class InputIt> priority_queue(InputIt first, InputIt last, const Compare& compare = Compare());

Complexity

Worst caseO(n) (make_heap: at most 3n comparisons)
Extra spaceO(n) for the container

Bottom-up heapify; cheaper than n separate pushes (O(n log n)).

Tested example

const std::vector<int> values{9, 4, 7, 1, 8, 2};
std::priority_queue<int> heap(values.begin(), values.end());  // make_heap: O(n)
assert(heap.top() == 9);
std::vector<int> raw = values;  // the same with the algorithms on a plain vector
std::make_heap(raw.begin(), raw.end());
assert(raw.front() == 9);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/priority_queue_examples.cpp

Parameters

first, last
The initial elements.

Behaviour

Returns
A new priority queue.
Errors and preconditions
Exceptions from copying or comparing.
Changes
Creates the heap.
Memory and invalidation
One container fill.