且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您可以在迭代时从 std::list 中删除元素吗?

更新时间:2023-01-17 18:02:36

您必须先增加迭代器(使用 i++),然后移除前一个元素(例如,使用 i++ 的返回值).您可以将代码更改为 while 循环,如下所示:

You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so:

std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
    bool isActive = (*i)->update();
    if (!isActive)
    {
        items.erase(i++);  // alternatively, i = items.erase(i);
    }
    else
    {
        other_code_involving(*i);
        ++i;
    }
}