Open In App

GFact | How to erase just one sample in std::multiset

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In std::multiset is there a function or algorithm to erase just one sample (unicate or duplicate) if an element is found? Curious to know the answer? This GFact will help you do just that.

But first, let us quickly understand what is a multiset.

What is Multiset?

Multisets are a type of associative container similar to the set, with the exception that multiple elements can have the same values.

What happens if we try to erase just one sample in std::multiset??

Well Let’s try it. Consider the below code that tries to erase only the once duplicate occurrence of value 2:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    multiset<int> s ({ 1, 1, 2, 2, 2, 3, 4, 5, 5 });
 
    // now erase one occurrence of 2
    s.erase(2);
 
    // now print the elements
    for (auto val : s) {
        cout << val << ' ';
    }
    cout << '\n';
 
    return 0;
}


Expected Output:

1 1 2 2 3 4 5 5 
(Just once duplicate occurrence of 2 ersaed)

Actual Output:

1 1 3 4 5 5
(All occurrences of 2 are ersaed)

Why doesn’t Multiset allow to erase just one sample?

The reason lies in the official definition of the erase() method in std::multiset.

size_type erase (const value_type& val);

where val is the Value to be removed from the multiset. All elements with a value equivalent to this are removed from the container.

So if you use a value as a parameter in the erase() function in a multiset, then all elements having same value than this passed value will be erased.

Then, How to erase just one sample in std::multiset?

Well to erase just one occurrence of a value in multiset, there is no direct way, but a workaround to do the same:

  • Try to delete element by iterator pointing to that element.
  • Iterator can be found using a find method of multiset.

Let us see with an example:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    multiset<int> s ({ 1, 1, 2, 2, 2, 3, 4, 5, 5 });
 
    // now erase one occurrence of 2
    // using iterator
    s .erase(s .find(2));
 
    // now print the elements
    for (auto val : s) {
        cout << val << ' ';
    }
    cout << '\n';
    // 1 1 2 2 3 4 5 5
    return 0;
}


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // Creating a List to simulate multiset behavior
        List<int> list = new List<int> { 1, 1, 2, 2, 2, 3, 4, 5, 5 };
 
        // Erasing one occurrence of 2
        list.Remove(2);
 
        // Printing the elements
        foreach (var val in list)
        {
            Console.Write(val);
        }
        Console.WriteLine();
        // Output: 11223455
    }
}


Output

1 1 2 2 3 4 5 5 




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads