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}
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.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
cout << "Original set : " ;
for ( auto i : s) {
cout << i << " " ;
}
cout << endl;
s.erase(40);
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
2. Removing an element by its index
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.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
cout << "Original set : " ;
for ( auto i : s) {
cout << i << " " ;
}
cout << endl;
int n = 3;
auto it = next(s.begin(), n);
s.erase(it);
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
3. 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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
s.insert(50);
cout << "Original set : " ;
for ( auto i : s) {
cout << i << " " ;
}
cout << endl;
auto it = s.find(40);
if (it != s.end())
s.erase(it);
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
Last Updated :
27 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...