- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Last element of vector in C++ (Accessing and updating)
In this article, we will be discussing the ways of accessing and updating the last element of a vector in C++.
What is a vector template?
Vectors are sequence containers whose size is changed dynamically. A container is an object that holds data of the same type. Sequence containers store elements strictly in a linear sequence.
Vector container stores the elements in contiguous memory locations and enables direct access to any element using a subscript operator []. Unlike arrays, the vector’s size is dynamic. The storage of the vector is handled automatically.
Definition of vector
Template <class T, class Alloc = allocator<T>> class vector;
Parameters of vector
The function accepts the following parameter(s) −
T − This is the type of element contained.
Alloc − This is the type of allocator object.
How can we access the last element of vector?
To access the last element of the vector we can use two methods:
Example
using back() function
#include <bits/stdc++.h> using namespace std; int main(){ vector<int> vec = {11, 22, 33, 44, 55}; cout<<"Elements in the vector before updating: "; for(auto i = vec.begin(); i!= vec.end(); ++i){ cout << *i << " "; } // call back() for fetching last element cout<<"\nLast element in vector is: "<<vec.back(); vec.back() = 66; cout<<"\nElements in the vector before updating: "; for(auto i = vec.begin(); i!= vec.end(); ++i){ cout << *i << " "; } return 0; }
Output
If we run the above code it will generate the following output −
Elements in the vector before updating: 11 22 33 44 55 Last element in vector is: 55 Elements in the vector before updating: 11 22 33 44 66
Example
using size() function
#include <bits/stdc++.h> using namespace std; int main(){ vector<int> vec = {11, 22, 33, 44, 55}; cout<<"Elements in the vector before updating: "; for(auto i = vec.begin(); i!= vec.end(); ++i){ cout << *i << " "; } // call size() for fetching last element int last = vec.size(); cout<<"\nLast element in vector is: "<<vec[last-1]; vec[last-1] = 66; cout<<"\nElements in the vector before updating: "; for(auto i = vec.begin(); i!= vec.end(); ++i){ cout << *i <<" "; } return 0; }
Output
If we run the above code it will generate the following output −
Elements in the vector before updating: 11 22 33 44 55 Last element in vector is: 55 Elements in the vector before updating: 11 22 33 44 66