25

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Avinash
  • 12,851
  • 32
  • 116
  • 186
  • 1
    A possible fix might be to swap the keys and values, this might not be an option for all reading this, but could be for some. – dangerousdave Oct 12 '12 at 11:07
  • Does this answer your question? [How to remove a specific pair from a C++ multimap?](https://stackoverflow.com/questions/3952476/how-to-remove-a-specific-pair-from-a-c-multimap) – Ciro Santilli OurBigBook.com Jan 08 '20 at 15:57

2 Answers2

20

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);
}
Nikola Smiljanić
  • 26,745
  • 6
  • 48
  • 60
  • Thanks This works for me, I was looking for using remove_if algorithms. – Avinash Jan 22 '10 at 10:18
  • I'm afraid `remove_if` from `` only works for containers where it is possible to reassign values (vector, deque, list - except suboptimal for the last) doing `*it1 = *it2`. This is not possible for map, as it might break the ordering. – UncleBens Jan 22 '10 at 16:28
  • @nietaki: No, the code does what the comments say. It removes all elements from the map where the value is even. Now remove your down-vote :) – Nikola Smiljanić Feb 02 '12 at 15:05
  • @nietaki Why should it? Isn't it exactly equivalent to your example only introducing an additional temporary variable? In addition to Nikola's demand, deleting your obsolete answer would be appropriate, too. – Christian Rau Feb 02 '12 at 15:08
  • I think putting `Multimap::iterator erase_iter = iter++;` in one statement is confusing. – Antonio Apr 05 '16 at 16:04
3

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)

Scrontch
  • 3,275
  • 5
  • 30
  • 45