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; } |
chevron_right
filter_none
Output :
50 100
1) 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; } |
chevron_right
filter_none
Output :
50 100
Recommended Posts:
- How to find the maximum element of a Vector using STL in C++?
- How to find the minimum and maximum element of a Vector using STL in C++?
- Accessing array out of bounds in C/C++
- Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
- How to erase an element from a vector using erase() and reverse_iterator?
- vector::front() and vector::back() in C++ STL
- vector::empty() and vector::size() in C++ STL
- vector :: cbegin() and vector :: cend() in C++ STL
- vector::crend() & vector::crbegin() with example
- vector::push_back() and vector::pop_back() in C++ STL
- vector::at() and vector::swap() in C++ STL
- vector::begin() and vector::end() in C++ STL
- Vector in C++ STL
- How does a vector work in C++?
- Modifiers for Vector in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



