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
#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; }
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),
Next, we have used the erase() function that searches for the name Kriti and removes it from the set.
x.erase("Kriti");
And we get the below output,
The Clear() Method can be used to remove all the elements from the set.
#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; }
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,
Next, we have used the clear() function that removes all the elements from the set making the set empty.