Open In App

How to Find Second to Last Element in a Vector in C++?

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

In C++, vectors are dynamic array containers that can change size automatically during runtime and provide random access to their elements. In this article, we will learn how to find the second to last element in a vector in C++.

Example:

Input:
myVector = {1, 2, 3, 1, 2, 3}

Output:
Second to Last Element: 2

Find Second to Last Element in a Vector in C++

In C++, we can use the std::vector:rbegin() iterator, which returns the reverse iterator, allowing us to traverse the vector in the reverse direction. We can use this reverse iterator to find the second to last element in the vector just by incrementing it by one and dereferencing.

C++ Program to Find Second to Last Element in a Vector

C++




// C++ program to find the second to last element in a
// vector
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> vec = { 1, 2, 3, 4, 5 };
  
    // Check if the vector has at least two elements
    if (vec.size() >= 2) {
        // Retrieve the second to last element
        int secondLast = vec[vec.size() - 2];
        cout << "The second to last element is: "
             << secondLast << "\n";
    }
    else {
        cout << "The vector does not have a second to last "
                "element.\n";
    }
  
    return 0;
}


Output

The second to last element is: 4

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

We can also find the last element by first finding the size of the array and then using (size – 2) and index.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads