只从具有重复键的多映射中删除一个元素

Remove only one element from multimap with duplicate keys

本文关键字:删除 元素 一个 映射      更新时间:2023-10-16

我有一个带有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;
    }
}