Open In App

How to Delete an Element from a Multiset in C++?

In C++, a multiset is a container that stores elements in a specific order. Multiple elements can have the same values. In this article, we will learn how to delete a specific element from a multiset.

Example:



Input:
myMultiset = {5, 2, 8, 5, 8, 8};
Element to delete: 8

Output:
myMultiset = {5, 2, 5, 8, 8}

Delete an Element from a Multiset in C++

To delete a specific element from a std::multiset in C++, we can use the std::multiset::erase() function. This function removes all elements with the given value from the multiset which is passed as an argument. If we want to remove only one occurrence of an element, we need to find an iterator to the element and then use the erase() function.

C++ Program to Delete an Element from a Multiset




// C++ Program to delete an element from a multiset
#include <iostream>
#include <set>
using namespace std;
  
// Driver Code
int main()
{
    multiset<int> set = { 1, 2, 2, 3, 4, 4, 5, 4 };
  
    int element = 4;
  
    // Find the occurrence of the element
    auto i = set.find(element);
  
    // Check if the element exists before erasing it
    if (i != set.end()) {
        // after erase the element
        set.erase(i);
    }
    else {
        cout << "Element " << element << " not found."
             << endl;
    }
  
    // Print after deletion
    for (const auto& e : set) {
        cout << e << " ";
    }
    cout << endl;
  
    return 0;
}

Output

1 2 2 3 4 4 5 

Time Complexity: O(logN)
Space Complexity: O(1)

Article Tags :