Remove only one item from unordered_multiset

3.3k Views Asked by At

I want to erase a specific element from std::unordered_multiset, but when I try with erase function, it eliminates all the items, no matter how many they are.
For example:

std::unordered_multiset<int> M;
M.insert(1);
M.insert(1);
M.insert(1);
std::cout<<M.count(1)<<std::endl;

M.erase(1);
std::cout << M.count(1) << std::endl;

I expect this to print 3 then 2. But it prints 3 then 0. So how to remove only one item?

1

There are 1 best solutions below

3
On BEST ANSWER

You can use another erase overload:

std::unordered_multiset<int> s { 1, 2, 2, 3, 3, 3 };

const auto it = s.find(2);

if (it != s.end())
    s.erase(it);

Live version