Open In App

How to Find the Last Occurrence of an Element in a Set in C++?

In C++, a set is a container that stores unique elements in a sorted order and elements are accessed and traversed using iterators. In this article, we will learn how to find the last occurrence of a specific element in a set in C++.

Example



Input:
set<int> s = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Key = 5
Output: The last occurrence of 5 is at index 4.

Last Occurrence of Element in a Set in C++

To find the last occurrence of an element in a std::set, we can use the std::find() function with the reverse iterators using std::set::rbegin() and std::set::rend(). The find() function returns the iterator to the first occurrence of the given range and reverse iterators make the find() function traverse the range in the reverse direction.

C++ Program to Find the Position of Last Occurrence of Element in Set

The below program demonstrates the use of reverse iterators to find the last occurrence of an element in the set.






// C++ program to illustrate how to find the last occurence
// of a element in a set
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // Create set
    set<int> mySet = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  
    // Choose the desired element
    int desiredElement = 5;
  
    auto rit = find(mySet.rbegin(), mySet.rend(),
                    desiredElement);
  
    // If element doesn't exist
    if (rit == mySet.rend()) {
        cout << "Element not found!" << endl;
    }
  
    auto idx = distance(mySet.begin(), rit.base()) - 1;
    cout << "Last occurrence of " << desiredElement
         << " is found at position: " << idx + 1 << endl;
  
    return 0;
}

Output
Last occurrence of 5 is found at position: 5

Time Complexity: O(N), where N is the size of the set.
Auxiliary Space: O(1)

Note: Here, we’re assuming that there is only single occurence of each element in a set.

Article Tags :