C++ .back()
Anonymous contributor
Published Oct 30, 2025
Contribute to Docs
C++ .back() Syntax
queueName.back();
Parameters:
The C++ .back() method takes no parameters.
Return value:
Returns a reference to the element at the end of the queue.
Example 1: Basic usage of C++ .back()
This example uses C++ .back() to access the last element of the queue:
#include <iostream>#include <queue>using namespace std;int main() {// Declaring a queuequeue<int> q;// Inserting int elements into the queueq.push(10);q.push(20);q.push(30);// Print the last element of the queuecout <<"Last element: " << q.back() << endl;}
Here is the output of this code:
Last element: 30
Example 2: Using C++ .back() with .push()
This example uses C++ .back() to return the last element of the queue after we used .push():
#include <iostream>#include <queue>using namespace std;int main () {queue<string> q;q.push("Jhon");q.push("Bob");q.push("Doe");cout <<"Last element: " << q.back() << endl;q.push("Alice");cout <<"Last element after push: " << q.back() << endl;}
Here is the output of this code:
Last element: DoeLast element after push: Alice
Codebyte Example: Modifying the Last Element Using C++ .back()
This codebyte example uses C++ .back() to modify the last element of the queue:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours