Open In App

How to Remove All Occurrences of an Element from Multiset in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a multiset is a container that stores a sorted collection of elements in sorted order, and we can also insert duplicate elements. In this article, we will learn how to remove all the occurrences of a specific element in C++.

Example

Input: 
myMultiset = {10, 10, 10, 20, 30, 40};
Target= 10

Output:
myMultiset = {20, 30, 40}

Remove All Occurrence of an Element from Multiset in C++

To remove all occurrences of a specific element from a std::multiset, we can use the std::multiset::erase() method where we provide a specific value to erase(), and it will remove all elements that are equal to that value from the multiset.

C++ Program to Erase All Occurrences of an Element in a Multiset

The below example demonstrates how we can use erase() method of multiset to remove all occurrences of a specific element from a multiset in C++ STL.

C++




// C++ program to remove all occurrences of an element from
// a multiset
  
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // Defining a Multiset
    multiset<int> myMultiset{ 10, 10, 10, 20, 30, 40 };
  
    // Set the required number to be removed from set
    int target = 10;
  
    // call the erase function.
    myMultiset.erase(target);
  
    // Print elements after removing the elements.
    cout << "Elements of multiset after removal are: ";
    for (auto num : myMultiset) {
        cout << num << " ";
    }
  
    return 0;
}


Output

Elements of multiset after removal are: 20 30 40 

Time Complexity: O(M log N), where M is the occurrences of the elements and N is the total number of elements.
Auxilliary Space: O(N)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads