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

 Live Demo

#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

 Live Demo

#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

Updated on: 22-Apr-2020

438 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements