只从具有重复键的多映射中删除一个元素
Remove only one element from multimap with duplicate keys
我有一个带有Note对象的多映射,我只想从中删除一个对象。可以有多个Note对象使用相同的键。问题是,现在也有不在我指定的关键范围内的对象被删除:
long key = note.measureNumber * 1000000 + note.startTime; // = 2000001
multimap<long, Note>::iterator it;
for (it = noteList.lower_bound(key); it != noteList.end() && it->first < (key + 1); it++) {
if(it->second.frequency == note.frequency){
noteList.erase(it);
}
}
当我用2000001
键运行这个代码时,我可以擦除正确的对象,但另一个用1000017
键的对象也会被擦除。不过,这两个对象的频率相同。
你知道我的for循环出了什么问题吗?
EDIT:要明确的是,我只想检查具有一个特定键的对象(在本例中为2000001
),迭代器不需要查看具有与该键不同键的对象
使用迭代器调用erase()将使其无效,因此您无法继续使用它。
请参阅从std::multimap<>中删除项目后,我是否可以继续使用迭代器
一旦擦除迭代器,它就会失效。如果您希望在遍历映射时从映射中擦除,则需要更改代码。试试这个:
multimap<long, Note>::iterator it;
for (it = noteList.lower_bound(key); it != noteList.end() && it->first < (key + 1);) {
if(it->second.frequency == note.frequency){
noteList.erase(it++);
}
else
{
++it;
}
}
如前所述,擦除迭代器会使其无效。我想指出您在代码方面的一些低效之处:您不需要迭代,直到循环结束。考虑一下:
for (it = noteList.lower_bound(key); it != noteList.upper_bound(key) && it->first == key; it++)
{
if(it->second.frequency == note.frequency)
{
noteList.erase(it++);
}
else
{
++it;
}
}
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 从矢量中删除元素后出现隔离错误
- 如何使用remove_if从矢量中删除元素
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++映射不删除元素
- 如何从标准::元组中删除元素?
- 在动态数组中添加/删除C++元素
- 如何通过比较彼此的成员从QStringList中删除元素
- 如何修复从矢量中删除元素的错误?
- 从 std::set 中删除元素,同时在 C++17 中迭代该元素
- 使用remove_if从矢量中删除元素
- 用C++从三维矢量中删除元素
- 从对象数组中删除元素
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ - 按自定义数据类型向量的值删除元素
- 从任意容器中廉价删除元素的惯用方法?
- 从数组中删除元素不起作用的函数
- 删除元素 BST
- 从向量中删除元素时未处理的异常