Last element of vector in C++ (Accessing and updating)
In C++ vectors, we can access last element using size of vector using following ways.
1) Using size()
#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{10, 20, 30, 40, 50}; // Accessing last element int n = v.size(); cout << v[n - 1] << endl; // modifying last element v[n - 1] = 100; cout << v[n - 1] << endl; return 0;} |
Output :
50 100
2) Using back() We can access and modify last value using back().
#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{10, 20, 30, 40, 50}; // Accessing last element cout << v.back() << endl; // modifying last element v.back() = 100; cout << v.back() << endl; return 0;} |
Output :
50 100
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.




