VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-find-all-occurrences-of-an-element-in-a-set-in-cpp/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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


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)


Comment
Article Tags: