Removing an element by an iterator

Another approach to removing an element from a set is by using an iterator and erase() function. In this way, we can remove the element from the set to which the iterator is pointing to. 

Example:

C++




// C++ program to remove
// an element from set
// Removing an element by an iterator
#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    set<int> s;
  
    // Inserting values in set
    s.insert(10);
    s.insert(20);
    s.insert(30);
    s.insert(40);
    s.insert(50);
  
    // Original set
    cout << "Original set : ";
    
    for (auto i : s) {
        cout << i << " ";
    }
    
    cout << endl;
  
    // Removing element
    // using iterator
    auto it = s.find(40);
  
    // Checking is element is present in set or not
    // And if present then Removing that element
    if (it != s.end())
        s.erase(it);
  
    // Set after Removing
    // an element
    cout << "Set after removing an element : ";
  
    for (auto i : s) {
        cout << i << " ";
    }
  
    return 0;
}


Output

Original set : 10 20 30 40 50 
Set after removing an element : 10 20 30 50 


Different Ways to Remove an Element From Set in C++ STL

Prerequisite: Set in C++

There are multiple ways to remove an element from the set. These are as follows:

  • Removing an element by its value
  • Removing an element by its index
  • Removing an element by an iterator

Example:

Input set s={10, 20, 30, 40, 50}   ,  value=40

// Removing 40 from the set

Output set s={10, 20, 30, 50} 

Similar Reads

1. Removing an element by its value

In this approach, we will delete an element from a set by providing its value in erase() function....

2. Removing an element by its index

...

3. Removing an element by an iterator

In this approach, we will delete an element by iterating the set to the index at which we want to delete the element. This can be done using next() function in C++. Then we will pass that iterator pointing to that index in erase() function to remove that element....

Contact Us