Open In App

How to Find All Occurrences of an Element in a Set in C++?

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

Finding the all occurrences of a specific element in a set using the C++ STL is a very efficient process that is done with the help of std::set::distance() member function. In this article, we’ll explore how to find the first element in a set using the C++ STL.

For Example,

Input:
mySet = {1, 2, 4, 3, 8, 4, 7, 8, 6, 4}
Element = 4

Output:
Index = 2 because occurrences of any element in a set is always 1, so consider the first Occurence of the elment.

Find all Occurrences of a Specific Element in std::set in C++

To find all occurrences of a specific element from a set in C++, we can iterate over the set and print the indices where the target integer is found.

Note: Occurrences of any element in a set is always 1. so the first Occurence will be the Last Occurrence of the element in set.

C++ Program to Find All Occurrences of an Element in a Set

C++




// C++ Program to illustrate how to Find All Occurrences of
// a Specific Element in a Set
#include <iostream>
#include <set>
using namespace std;
  
// Driver Code
int main()
{
  
    std::set<int> mySet
        = { 1, 2, 3, 4, 1, 5, 1, 6, 7, 8, 1 };
    int target = 4;
    bool found = false;
  
    cout << "Element " << target << " found at indices: ";
  
    // Iterate over the set elements
    size_t index = 0;
    for (auto it = mySet.begin(); it != mySet.end();
         ++it, ++index) {
        // If the current element matches the target
        if (*it == target) {
  
            cout << index << " ";
            // Set the found flag to true
            found = true;
        }
    }
  
    // If the target element is not found, print a message
    if (!found) {
        cout << "Element " << target
             << " not found in the set.\n";
    }
  
    return 0;
}


Output

Element 4 found at indices: 3 

Time complexity: O(logN), where N is the number of elements in the setl.
Space complexity: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads