Horje
How to Find Last Occurrence of an Element in Vector?

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++

// C++ program to find the last occurence of an element
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Vector V is the targeted vector
    vector<int> V = { 2, 5, 9, 8, 5, 4, 9, 12, 9, 12 };
    // To find the last occurrence of element 9.
    int key = 9;
  
    // Finding the last occurrence of m in vector V
    auto it = find(V.rbegin(), V.rend(), key);
  
    int res = -1;
    if (it != V.rend()) {
        // Calculate the index of the last occurrence
        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)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Merge Multiple Vectors into a List in C++? How to Merge Multiple Vectors into a List in C++?
How to Reverse a String in Place in C++? How to Reverse a String in Place in C++?
How to Find the Smallest Number in an Array in C++? How to Find the Smallest Number in an Array in C++?
How to Find Largest Number in an Array in C++? How to Find Largest Number in an Array in C++?
How to Access the Last Element in a Vector in C++? How to Access the Last Element in a Vector in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13