views:

57

answers:

1
#include <map>

...

multimap<char,int> first;

first.insert(pair<char,int>('a',10));
first.insert(pair<char,int>('b',15));
first.insert(pair<char,int>('b',20));
first.insert(pair<char,int>('c',25));

Say I now want to remove one of the pairs I have just added to the map.

I have examples to remove an entire key entry, which for key 'b' would remove both 'b',15 and 'b',20.

But what is the code to remove just, say, the pair 'b',20?

+7  A: 

You can use std::multimap<char, int>::equal_range, which will give you an iterator range containing all pairs which have a certain key. So if you look for 'b', you will get an iterator range containing all pairs which have 'b' as the key.

You can then simply iterate over the range, and erase any pair you see fit, by erasing the iterator.

multimap<char,int> mymap;

mymap.insert(pair<char,int>('a',10));
mymap.insert(pair<char,int>('b',15));
mymap.insert(pair<char,int>('b',20));
mymap.insert(pair<char,int>('c',25));

typedef multimap<char, int>::iterator iterator;
std::pair<iterator, iterator> iterpair = mymap.equal_range('b');

// Erase (b,15) pair
//
iterator it = iterpair.first;
for (; it != iterpair.second; ++it) {
    if (it->second == 15) { 
        mymap.erase(it);
        break;
    }
}
Charles Salvia
Thanks a lot Charles, and for the code snippet too.
Jim Blackler