How to remove a specific pair from a C++ multimap?

19,003

Solution 1

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;
    }
}

Solution 2

In case you need to continue iterating after the first match you need to first retrieve an iterator to the next element since the erased iterator gets invalidated.

One way to achieve this, starting from C++11, is to use the return value of the erase function which is an iterator to the element that follows the last element removed (or multimap::end, if the last element was removed). Beware the key based version returns the number of elements erased, not an iterator.

Building on top of the valuable Charles Salvia answer, showing how to erase (b,15 ) pair, you get

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; ) {
    if (it->second == 15) { 
        it=mymap.erase(it);
    }
    else
        ++it;
}
Share:
19,003
Jim Blackler
Author by

Jim Blackler

I'm a software engineer with nearly 20 years commercial experience, and as a hobbyist even longer. I currently work for Google, before that you could find me in the videogames industry. I specialise in user-facing technology; browser and mobile handset applications.

Updated on June 12, 2022

Comments

  • Jim Blackler
    Jim Blackler almost 2 years
    #include <map>
    
    ...
    
    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));
    

    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?