How to Access the Last Element in a Vector in C++?
Last Updated :
13 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5 };
int lastElement = myVector.back();
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)
Share your thoughts in the comments
Please Login to comment...