How to Find Last Occurrence of an Element in Vector?
Last Updated :
13 Feb, 2024
In C++, the last occurrence of an element in a vector means the last time that element appeared in the vector if traversed from the start. In this article, we will learn how to find the last occurrence of a specific element in a vector in C++.
Example
Input:
vector<int> vec= {2, 5, 9, 8, 5, 4, 9, 12, 9, 12};
Key=9
Output:
The Last Occurrence of 9 is at index 8.
Position of Last Occurrence of Element in Vector in C++
To find the last occurrence of an element in a std::vector we can use the std::find with reverse iterators and iterate through the vector in reverse order. When we iterate in reverse order the first occurrence is the last occurrence of that element.
The std::vector::rbegin() function can be used to get the reverse iterator to the vector.
C++ Program to Find the Position of Last Occurrence of Element in Vector
The below program demonstrates the use of the find() function and reverse iterators to find the last occurrence of an element in the vector.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > V = { 2, 5, 9, 8, 5, 4, 9, 12, 9, 12 };
int key = 9;
auto it = find(V.rbegin(), V.rend(), key);
int res = -1;
if (it != V.rend()) {
res = V.rend() - it - 1;
}
cout << "The last occurrence of " << key << " is "
<< res;
return 0;
}
|
Output
The last occurrence of 9 is 8
Time Complexity: O(N), where N is the number of elements in the vector.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...