.back()
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.
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: 60The 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:
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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours