Open In App

How to Access the Last Element in a Vector in C++?

Last Updated : 16 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a vector of n elements, the task is to access the last element in C++.

Examples

Input: v = {11, 23, 9, 7};
Output: 7
Explanation: Since 7 is the last element of the vector.

Input: v = {1, 3, 11, 52};
Output: 52
Explanation: Since 52 is the last element of the vector.

Following are the different ways for accessing the last element of vector in C++:

Using vector::back() Method

The simplest way to access the last element of a vector is by using the std::vector::back() member function. This function returns the last element of the vector.

Example

C++
// C++ program to access the last element of
// a vector using std::back()
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 9, 7};
  
    // Accessing the last element of the vector 
    // with std::back() method
    int last = v.back();

    cout << last;
    return 0;
}

Output
7

Time Complexity: O(1)
Auxiliary Space : O(1)

Using vector::size() Method

In C++, std::vector is a zero indexed container, so the index of the last element is: size of the vector - 1. We can find size of the vector using std::vector::size() method. This function returns the size of the vector as integer.

Example

C++
// C++ program to show how to access the last
// element of a vector using size()-1
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 9, 7};
  
  	// Accessing the last element of the vector 
    // using index
    int last = v[v.size() - 1];

    cout << last;
    return 0;
}

Output
7

Time Complexity: O(1)
Auxiliary Space: O(1)

We can also use the std::vector::at() method to access the last element using its index value.

Using vector::end() Iterator

We can also access the last element of the vector end iterator which is returned by std::vector::end() method. The end iterator initially points to the theoretical element after the last element. We can decrement and dereference it to access the last element.

Example

C++
// C++ program to show how to access the last
// element of a vector using iterator
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 9, 7};

    // Iterator to the last element
    auto it = --v.end();

    cout << *it;
    return 0;
}

Output
7

Time Complexity: O(1)
Auxiliary Space: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads