In C++, back() lets you look at the newest element of a std::queue. This is the element that joined last, so it will be the last one to leave.
back() is the other end of the line from front(). Every push() puts a new element behind the old ones, so after a push() the new value is what back() returns. It does not remove anything.
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.back(...).
Syntax
Call back() on the queue. It takes no arguments.
C++
std::queue<int> q;
q.push(30);
q.push(50);
q.push(10);
int newest = q.back(); // 10, the last one pushed
Call
What it does
q.back()
Returns a reference to the newest element. You can read it or change it. The element stays in the queue.
q.back() // const queue
On a const queue it returns a const reference, so you can only read the value.
There is no function to remove the back element. A queue only removes from the front with pop(). If you need to take items out at the back too, use std::deque and its pop_back().
Library declarations
C++
reference back();
const_reference back() const;
// queue<T, Container> from <queue>
// back() returns c.back(), the last element of
// the underlying container (a deque by default).
Parameters
Parameter
Description
None
back() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
T&
A reference to the newest element. On a const queue it is a const T&.
Undefined behavior
If the queue is empty there is no element to return. Check empty() first.
C++ Examples
Example 1 — Read the Newest Element
Push three numbers, read both ends, then push one more. Only the back changes.