What is the queue.back() function in C++?
Overview
The back() method is used to get the last inserted element to the queue or to get the first element from the back of the queue.
In the diagram below, there is a queue, and the back() function will point to the last inserted element, such as 3.
Syntax
queue.back()
Parameters
The method has no parameters.
Return value
The method returns the last element of the queue.
Code
#include <iostream>#include <queue>using namespace std;int main() {queue<int> qu;qu.push(1);qu.push(2);qu.push(3);cout << "The back of the queue: " << qu.back();}
Explanation
- Lines 8–10: We insert the elements into the queue.
- Line 12: We use the
back()method to retrieve the last element of the queue is retrieved.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved