如何从C ++多重映射中删除特定的一对?
#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.
我有删除整个键条目的示例,对于键 b,它会同时删除 b,15和 b,20。
I have examples to remove an entire key entry, which for key 'b' would remove both 'b',15 and 'b',20.
但是仅删除 b对20的代码是什么?
But what is the code to remove just, say, the pair 'b',20?
您可以使用 std :: multimap< char,int> :: equal_range
,这将为您提供一个迭代器范围,其中包含具有特定键的所有对。因此,如果您查找 b,则会得到一个迭代器范围,其中包含所有以 b为键的对。
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;
}
}