C++ .back()

Anonymous contributor's avatar
Anonymous contributor
Published Oct 30, 2025
Contribute to Docs

The C++ .back() method is used to access the element at the back of the queue without removing it.

  • 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

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 queue
queue<int> q;
// Inserting int elements into the queue
q.push(10);
q.push(20);
q.push(30);
// Print the last element of the queue
cout <<"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: Doe
Last 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:

Code
Output
Loading...

All contributors

Contribute to 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