Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C++ - REMOVE FROM SET


How to remove an element from the set by its name/value?


Let us say, we have a set that contains three names, Mohan, Kriti and Salim. And we want to remove Kriti from the set.


It can be done with the erase() Method


Example :



#include <iostream>
#include <set>

using namespace std;


int main() {
        
    set<string> x; 
        
    x.insert("Mohan");
    x.insert("Kriti");
    x.insert("Salim");
    
    x.erase("Kriti");
        
    for (string data : x)  
    {  
        cout << data << endl;  
    }
        
    return 0;    
}


Output :



  Mohan
  Salim

So, in the above code we have created a set and initialised to the variable x.


set<string> x;

x.insert("Mohan");
x.insert("Kriti");
x.insert("Salim");

Below is how the values are positioned in the set(i.e. In sorted order),

java_Collections

Next, we have used the erase() function that searches for the name Kriti and removes it from the set.


x.erase("Kriti");
java_Collections


And we get the below output,

Output :



  Mohan
  Salim

How to remove all the elements from the set?


The Clear() Method can be used to remove all the elements from the set.


Example :



#include <iostream>
#include <set>

using namespace std;


int main() {
        
    set<string> x; 
        
    x.insert("Mohan");
    x.insert("Kriti");
    x.insert("Salim");
    
    x.clear();
        
    for (string data : x)  
    {  
        cout << data << endl;  
    }
        
    return 0;    
}


Output :




So, in the above code we have created a set and initialised to the variable x.


set<string> x;
x.insert("Mohan");
x.insert("Kriti");
x.insert("Salim");

Below is how the values are positioned in the set,

java_Collections

Next, we have used the clear() function that removes all the elements from the set making the set empty.