Open In App

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

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ program to remove all occurences of a specific
// element from set
  
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // creating a set
    set<int> mySet = { 1, 2, 3, 2, 4, 5, 2 };
  
    // Printing the initial set
    cout << "Before deletion: ";
    for (int elem : mySet) {
        cout << elem << " ";
    }
    cout << endl;
  
    int target = 2; // Element to remove
  
    // Find the first occurrence of the element to remove
    auto it = mySet.find(target);
  
    // Erase all occurrences of the element
    while (it != mySet.end()) {
        mySet.erase(it); // Erase the element
        it = mySet.find(target); // Find the next occurrence
    }
  
    // Print the set after deletion
    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.



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

Similar Reads