std::priority_queue<T> · C++

top

Returns the largest element (under Compare) without removing it.

const_reference top() const;

Complexity

Best caseO(1)
Worst caseO(1)
Extra spaceO(1)

c.front(): the heap keeps the top at index 0.

Tested example

std::priority_queue<int> heap;
assert(heap.empty());
heap.push(7);
assert(heap.top() == 7);  // constant time, nothing removed
assert(heap.size() == 1);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/priority_queue_examples.cpp

Behaviour

Returns
A const reference to the top element.
Errors and preconditions
Undefined behaviour on an empty queue.
Changes
Nothing.
Memory and invalidation
No allocation.