Open In App

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

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

C++ provides us with a vector data container which is a dynamic array that stores elements in a contiguous memory location. In this article, we’ll learn how to access the last element in a vector in C++ STL which is one of the fundamental operations.

For Example,

Input:
myVector = {1, 2, 3, 4, 5, 6}

Output:
Last Element: 6

Access the Last Element in a Vector in C++

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

Syntax of back() Function

myVector.back()

C++ Program to Access the Last Element in a Vector

C++




// C++ program to demonstrate how to access the last element
// of a vector
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initializing a new vector
    vector<int> myVector = { 1, 2, 3, 4, 5 };
  
    // Using back() function to retrieve the last element
    int lastElement = myVector.back();
  
    // Outputting the last element
    cout << "The last element is: " << lastElement << endl;
  
    return 0;
}


Output

The last element is: 5

In this example, myVector.back() returns a reference to the last element in the vector myVector, and we store it in the variable last element. Then, we simply print out the value of lastElement.

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads