C++ .back()

MamtaWardhani's avatar
Published Oct 29, 2025
Contribute to Docs

In C++, the .back() method returns a reference to the last element in a deque. It allows direct access to that element for reading or modifying without removing it.

Note: Calling .back() on an empty deque leads to undefined behavior. Check with .empty() before using .back().

  • 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

Syntax

dequeName.back();

Parameters:

This method does not take any parameters.

Return value:

Returns a reference to the last element of the deque. If the deque is const, it returns a const reference.

Example: Accessing and Updating the Last Element

This example retrieves the last number in a deque, updates it, and displays the change:

#include <deque>
#include <iostream>
int main() {
std::deque<int> scores = {45, 67, 89};
std::cout << "Last score: " << scores.back() << std::endl;
// Update the last element
scores.back() = 100;
std::cout << "Updated last score: " << scores.back() << std::endl;
return 0;
}

This program produces the following output:

Last score: 89
Updated last score: 100

Codebyte Example: Using .back() in a Conditional Check

This example shows how .back() can be used to verify or modify the final value in a deque:

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