c++stlseteraseunordered-multiset

Remove only one item from unordered_multiset


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?


Solution

  • 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