In C++, empty() tells you whether a std::priority_queue has no elements. It returns true for an empty queue and false when at least one element is waiting.
It is the safety check for the whole container. top() and pop() are undefined behavior on an empty queue, so you ask empty() first. A priority queue has no iterators, so while (!pq.empty()) is also the normal way to walk through every element.
This function is a member function of std::priority_queue<T>, declared in the <queue> header. It has been available since the first C++ standard, so every compiler supports it. You call it with a dot, for example pq.empty(...).
Syntax
Call empty() on the queue. It takes no arguments and returns a bool.
C++
std::priority_queue<int> pq;
bool a = pq.empty(); // true, nothing inside
pq.push(7);
bool b = pq.empty(); // false, one element inside
Call
What it does
pq.empty()
Returns true if the queue has no elements, otherwise false. It never changes the queue.
empty() is fast and runs in constant time. It is the same as asking pq.size() == 0, but it reads more clearly. Since C++20 the function is marked [[nodiscard]], so a compiler may warn if you call it and ignore the answer.
Library declarations
C++
[[nodiscard]] bool empty() const; // [[nodiscard]] since C++20
// priority_queue<T, Container, Compare> from <queue>
// empty() returns c.empty()
Parameters
Parameter
Description
None
empty() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
true
The queue has no elements.
false
The queue has at least one element.
C++ Examples
Example 1 — Check an Empty Queue
A new queue is empty. After one push() it is not. Use std::boolalpha to print true and false.
largestOr() receives the queue by const reference. empty() and top() are both const functions, so this is allowed.
For the empty queue, empty() is true, so the function returns the fallback -1 and never touches top().
For the filled queue, empty() is false, so top() is safe to call and returns the largest value 8.
Frequently Asked Questions
It returns true if the priority_queue has no elements, and false if it has at least one element.
Calling top() or pop() on an empty queue is undefined behavior. A quick if (!pq.empty()) check keeps your program safe.
A priority_queue has no iterators. Use while (!pq.empty()) { use pq.top(); pq.pop(); }. This also removes the elements one by one from the queue.
Yes. Both mean the queue holds no elements. empty() is the clearer way to write it and is the style most C++ programmers prefer.
There is no clear() function. Assign a new empty queue, such as pq = std::priority_queue<int>(); or swap with an empty one. Calling empty() afterwards returns true.