Erase All Elements Satisfying Given Condition From unordered_multiset in C++

In C++, an unordered_multiset is an associative container that stores elements in no particular order and allows multiple elements to have the same value. In this article, we will learn how to erase all elements satisfying specific criteria from an unordered_multiset in C++.

Example

Input:
mySet = {1,2,3,2,4,5,2};
criteriaToRemove = Element is even

Output:
After Deletion: 1 3 5

Erase Elements Satisfying Specific Criteria from an unordered_multiset in C++

To erase all elements satisfying specific criteria from an unordered_multiset, first define a function or a lambda function that specifies the criteria for element deletion and then iterate through the unordered_multiset and use the unordered_multiset::erase() function to erase all elements that satisfy that criteria.

C++ Program to Erase All Elements Satisfying Specific Criteria From an unordered_multiset

The below program demonstrates how we can erase all elements satisfying specific criteria from an unordered_multiset in C++ STL.

C++
// C++ program to Erase All Elements Satisfying Specific
// Criteria from an unordered_multiset in C++
#include <iostream>
#include <unordered_set>
using namespace std;

int main()
{

    // define unordered_multiset
    unordered_multiset<int> umset
        = { 1, 2, 2, 3, 4, 5, 4, 3 };

    cout << "Elements before removal: ";
    for (int num : umset) {
        cout << num << " ";
    }
    cout << endl;

    // creating a lamda function that checks if the given
    // number is even
    auto criteriaToRemove
        = [](int n) { return n % 2 == 0; };

    for (auto it = umset.begin(); it != umset.end();) {
        // checking if the number is even
        if (criteriaToRemove(*it)) {
            it = umset.erase(it);
        }
        else {
            ++it;
        }
    }

    cout << "Elements after removal: ";
    for (int num : umset) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Output
Elements before removal: 5 4 4 3 3 2 2 1 
Elements after removal: 5 3 3 1 

Time Complexity : O(N)
Auxilliary Space: O(1)

Note: In C++20, the erase_if() function can be used with an unordered_multiset to remove all elements that meet specific criteria which is passed as an argument to the erase_if() function along with unordered_multiset.



Contact Us