Get the last element from a vector in C++

In this tutorial, we will learn how to access the last element from a vector in C++.

In C++, we can get the last element of the vector by using the following two methods:

  1. Using size()
  2. Using back() 

We will understand how to use these methods.

Using size()

In this method, get the size of the vector and store it in a variable say length. To get the last element, pass length-1 in the subscript operator. This will give you the last element of the vector.

Let’s understand this with the help of a program:

#include <iostream>
#include <vector>
using namespace std;
int main()
{

    vector<int> numbs= { 14, 50, 16, 19, 69, 40 };
    int length = numbs.size();
    // Check if vector is not empty
    if(length > 0)
    {
        // Access the last element of vector
        int lastElement = numbs[length-1];
        cout<<"Last Element of vector is: "<< lastElement;
    }
    else
    {
        cout<<"Vector is Empty";
    }
    return 0;
}
Output

Last Element of vector is: 40

Using back()

In C++, the vector class provides a function back() which provides the reference to the last element of the vector. While using back()  make sure that the vector is not empty. If the vector will be empty it will cause undefined behavior.

Let’s understand the use of back() with the help of a program:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> numbs= {1, 22, 13, 20, 35, 56};
    // Get last element of vector
    int lastelem = numbs.back();
    // print last element of vector
    cout <<"The last element is "<<lastelem << endl;
    return 0;
}

 

Output

The last element is 56

Leave a Reply

Your email address will not be published. Required fields are marked *