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++
// C++ program to remove // an element from set // Removing an element by its value #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 s.erase(40); // 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}
Contact Us