C++ .back()

Anonymous contributor's avatar
Anonymous contributor
Published Oct 18, 2024
Contribute to Docs

The C++ .back() method is used to access the last element in a vector. It views or modifies the element without removing it from the vector. This method is primarily used to access the most recently added element.

  • 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

vectorName.back();

Example

The below example shows the use of .back() method in c++ vectors, here numbers is a vector which has 5 elements in it and it displays the last element in the vector with the help of the .back() method, then the last element in the vector is modifies and the modified value is displayed.

#include <iostream>
#include<vector>
//This is compulsory to include vectors while using vectors.
int main(){
std::vector<int>numbers = {10,20,40,50,60};
std::cout<<"The last element in the vector is: "<< numbers.back()<< std::endl;
numbers.back() = 80;
std::cout <<"The last element in the vector after modification is: "<<numbers.back() <<std::endl;
return 0;
}

The output of the above code:

The last element in the vector is: 60
The last element in the vector after modification is: 80

Codebyte Example

This codebyte example shows how a last element in the vector is accessed and modified using the back() method:

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