Using erase_If with Set in C++ STL
The erase_if function in C++20 is used to erase all the elements in the set satisfying the required condition. This condition is referred to as the predicate.
The syntax for the erase_if function is
erase_if(set, predicate);
The first argument of erase function is the set in which elements need to be erased. The second argument is the predicate which is the condition to be satisfied.
Example:
In this example, we are considering a set of the first 10 natural numbers and using the erase_if function to erase all odd elements from the set.
C++
#include <bits/stdc++.h> using namespace std; int main() { set< int > data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; cout << "Original set: " << endl; for ( auto e : data) cout << e << " " ; cout << endl; // predicate (the condition to be satisfied to erase elements) auto remove_odd = []( auto const & x) { return (x % 2) == 0; }; // calling erase_if function erase_if(data, remove_odd); cout << "After removing odd elements from the set " "using erase_if\n" ; for ( auto e : data) cout << e << " " ; cout << endl; return 0; } |
Output:
Original set: 1 2 3 4 5 6 7 8 9 10 After removing odd elements from the set using erase_if 1 3 5 7 9
Note: erase_if function is available in C++20 and GeeksForGeeks Compiler supports only till C++14 thus you will get an error if you will try running code here.
Please Login to comment...