In C++, empty() tells you whether a std::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. front(), back(), and pop() are undefined behavior on an empty queue, so you ask empty() first. A queue has no iterators, so while (!q.empty()) is also the normal way to walk through every element.
This function is a member function of std::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 q.empty(...).
Syntax
Call empty() on the queue. It takes no arguments and returns a bool.
C++
std::queue<int> q;
bool a = q.empty(); // true, nothing inside
q.push(7);
bool b = q.empty(); // false, one element inside
Call
What it does
q.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 q.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
// queue<T, Container> 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, and after pop() it is empty again. Use std::boolalpha to print true and false.