How to Remove All Occurrences of an Element from Multiset in C++?
Last Updated :
22 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
multiset< int > myMultiset{ 10, 10, 10, 20, 30, 40 };
int target = 10;
myMultiset.erase(target);
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)
Share your thoughts in the comments
Please Login to comment...