Avinash
Avinash

Reputation: 13267

STL Multimap Remove/Erase Values

I have STL Multimap, I want to remove entries from the map which has specific value , I do not want to remove entire key, as that key may be mapping to other values which are required.

any help please.

Upvotes: 25

Views: 11727

Answers (2)

Scrontch
Scrontch

Reputation: 3422

Since C++11, std::multimap::erase returns an iterator following the last removed element.

So you can rewrite Nikola's answer slightly more cleanly without needing to introduce the local erase_iter variable:

typedef std::multimap<std::string, int> Multimap;
Multimap data;

for (Multimap::iterator iter = data.begin(); iter != data.end();)
{
    // removes all even values
    if (iter->second % 2 == 0)
        iter = data.erase(iter);
    else
        ++iter;
}

(See also answer to this question)

Upvotes: 4

Nikola Smiljanić
Nikola Smiljanić

Reputation: 26863

If I understand correctly these values can appear under any key. If that is the case you'll have to iterate over your multimap and erase specific values.

typedef std::multimap<std::string, int> Multimap;
Multimap data;

for (Multimap::iterator iter = data.begin(); iter != data.end();)
{
    // you have to do this because iterators are invalidated
    Multimap::iterator erase_iter = iter++;

    // removes all even values
    if (erase_iter->second % 2 == 0)
        data.erase(erase_iter);
}

Upvotes: 20

Related Questions