Open In App

Using erase_If With Unordered_Set in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Unordered_set in C++

The last standard released in 2017 is C++ 17, C++20 is going to be the latest standard with many new features included in it. Among all these new features erase_If  is a unique new feature that returns “the count of erased elements”.

Template:

erase_if (container , f(O) -> bool )

where f(O) is a Unary function that returns “true” or “false” according to the conditions given. If it returns true the element is removed and it’s not removed when it returns false, and in return, the function erase_if() returns the count of removed objects.

Now using erase_If() with Unordered_Set in C++20 will return the equivalent count of numbers as returned by a normal code snippet.

Code snippet:

unordered_set<int> data { 3, 2, 4, 5, 5, 5, 6, 7, 2, 1, 10, 15 };
auto old_size=data.size();

for (auto it=data.begin(); it !=data.end(); ) {
    if (*it %2==0) {
        it=data.erase(it);
    }

    else {
        it++;
    }
}

return old_size - data.size();

The above code snippet returns the count of erased even numbers from the unordered_set. The same task can be done easily in one line using erase_if( ) in C++20. The following program is to remove all the even numbers from the given unordered_set and prints the count of the removed elements from the unordered_set using erase_if() in C++20.

Time Complexity: O(N), because of traversing only once.
Auxiliary Space: O(N), as hashing is used.

Code:

C++




// C++ program to illustrate
// Implementation of erase_if()
// to remove all the even numbers
#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    // Implementation of the unordered_set.
    unordered_set<int> data{ 3, 2, 4, 5, 5,  5,
                             6, 7, 2, 1, 10, 15 };
  
    cout << "Old_Data in unordered_set :";
  
    // To Print the Old unordered_set.
    for (auto x : data) {
        cout << x << " ";
    }
    cout << "\n";
  
    // The lambda function to return true or false .
    auto even_nos = [](int num) { return (num % 2) == 0; };
  
    // To remove all the even numbers and
    // Print the count of it.
    int count = erase_if(data, even_nos);
  
    cout << "Items erased :" << count << "\n";
    cout << "The Odd numbers are :";
  
    // To Print the New unordered_set.
    for (auto x : data) {
        cout << x << " ";
    }
  
    return 0;
}


Output:

Old_Data in unordered_set : 10 1 7 6 5 4 15 2 3 
Items erased : 4
The Odd numbers are : 1 7 5 15 3 


Last Updated : 27 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads