How to remove a specific pair from a C++ multimap?(如何从 C++ 多图中删除特定对?)
问题描述
#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?
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;
}
}
这篇关于如何从 C++ 多图中删除特定对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 C++ 多图中删除特定对?


基础教程推荐
- C语言3个整数的数组 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- 对 STL 容器的安全并行只读访问 2022-10-25
- C语言数组 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 总计将在节日礼物上花多少钱 1970-01-01
- C++多态 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23