How to Remove All Occurrences of an Element from a Set in C++?
Last Updated :
01 Mar, 2024
In C++, a set is an associative container that stores unique elements in a sorted order. In this article, we will learn how to remove all occurrences of a specific element from a set in C++.
Example:
Input:
mySet = {1,2,3,4,5};
target= 2
Output:
After Deletion: 1 3 4 5
Delete All Occurrences of an Element from a Set in C++
To delete all occurrences of a given element from a set first, search for the element to be removed using the std::set::find function if found erase the occurrence of that element from the set using the std::set::erase function.
Note: The set contains only unique elements, so there will be only one occurrence of an element in the set.
C++ Program to Remove All Occurrences of an Element from Set
The below program demonstrates how we can remove all occurrences of a specific element from the set in C++ STL.
C++
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 1, 2, 3, 2, 4, 5, 2 };
cout << "Before deletion: " ;
for ( int elem : mySet) {
cout << elem << " " ;
}
cout << endl;
int target = 2;
auto it = mySet.find(target);
while (it != mySet.end()) {
mySet.erase(it);
it = mySet.find(target);
}
cout << "After Deletion: " ;
for ( int elem : mySet) {
cout << elem << " " ;
}
cout << endl;
return 0;
}
|
Output
Before deletion: 1 2 3 4 5
After Deletion: 1 3 4 5
Time Complexity: O(n log(n)), here n is the number of elements in the set.
Auxiliary Space: O(1)
Note: Here, we’re assuming that there is only single occurence of each element in a set.
Share your thoughts in the comments
Please Login to comment...