我有这样的代码:

for (std::list<item*>::iterator i=items.begin();i!=items.end();i++)
{
    bool isActive = (*i)->update();
    //if (!isActive) 
    //  items.remove(*i); 
    //else
       other_code_involving(*i);
}
items.remove_if(CheckItemNotActive);

我想在更新后立即删除不活跃的项目,以避免再次浏览列表。但是如果我添加注释掉的行,当我到达i++时,我得到一个错误:“列表迭代器不可递增”。我尝试了一些在for语句中不增加的替代方法,但我不能让任何东西工作。

什么是最好的方法来删除项目,因为你正在走std::列表?


当前回答

我总结了一下,下面是这三种方法的例子:

1. 使用while循环

list<int> lst{4, 1, 2, 3, 5};

auto it = lst.begin();
while (it != lst.end()){
    if((*it % 2) == 1){
        it = lst.erase(it);// erase and go to next
    } else{
        ++it;  // go to next
    }
}

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

2. 在列表中使用remove_if成员函数:

list<int> lst{4, 1, 2, 3, 5};

lst.remove_if([](int a){return a % 2 == 1;});

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

3.使用std::remove_if函数结合erase成员函数:

list<int> lst{4, 1, 2, 3, 5};

lst.erase(std::remove_if(lst.begin(), lst.end(), [](int a){
    return a % 2 == 1;
}), lst.end());

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

4. 使用for循环时,应注意更新迭代器:

list<int> lst{4, 1, 2, 3, 5};

for(auto it = lst.begin(); it != lst.end();++it){
    if ((*it % 2) == 1){
        it = lst.erase(it);  erase and go to next(erase will return the next iterator)
        --it;  // as it will be add again in for, so we go back one step
    }
}

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2 

其他回答

你必须先增加迭代器(使用i++),然后删除前一个元素(例如,通过使用i++的返回值)。你可以像这样将代码更改为while循环:

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;
    }
}

你想做的是:

i= items.erase(i);

这将正确地更新迭代器,使其指向您删除的迭代器之后的位置。

向后迭代避免了在要遍历的剩余元素上擦除一个元素的效果:

typedef list<item*> list_t;
for ( list_t::iterator it = items.end() ; it != items.begin() ; ) {
    --it;
    bool remove = <determine whether to remove>
    if ( remove ) {
        items.erase( it );
    }
}

PS:看看这个,例如,关于向后迭代。

PS2:我没有彻底测试它是否处理好擦除元素在结束。

使用std::remove_if算法。

编辑: 使用集合的工作应该是这样的:

准备收集。 收集过程。

如果你不把这些步骤混在一起,生活会更容易。

std:: remove_if。或者list::remove_if(如果你知道你使用list而不是TCollection) std:: for_each

删除只会使指向被删除元素的迭代器失效。

所以在这种情况下,删除*i后,i是无效的,你不能对它做增量操作。

你能做的是首先保存要删除的元素的迭代器,然后增加迭代器,然后删除保存的迭代器。