How to remove a specific pair from a C++ multimap?
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;
}
}
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;
}