Open In App
Related Articles

Last element of vector in C++ (Accessing and updating)

Improve Article
Improve
Save Article
Save
Like Article
Like

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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 10 Sep, 2020
Like Article
Save Article
Previous
Next
Similar Reads