C++ .back()
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().
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 elementscores.back() = 100;std::cout << "Updated last score: " << scores.back() << std::endl;return 0;}
This program produces the following output:
Last score: 89Updated 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:
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