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()

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


Output :



50
100

1) Using back() We can access and modify last value using back().

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


Output :

50
100


My Personal Notes arrow_drop_up

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.




Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.