您可以在迭代时从 std::list 中删除元素吗? [英] Can you remove elements from a std::list while iterating through it?

查看:34
本文介绍了您可以在迭代时从 std::list 中删除元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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++ 时会出现错误:List iterator not incrementable".我尝试了一些在 for 语句中没有增加的替代方法,但我无法得到任何工作.

I'd like remove inactive items immediately after update them, inorder to avoid walking the list again. But if I add the commented-out lines, I get an error when I get to i++: "List iterator not incrementable". I tried some alternates which didn't increment in the for statement, but I couldn't get anything to work.

在走 std::list 时删除项目的最佳方法是什么?

What's the best way to remove items as you are walking a std::list?

推荐答案

您必须先增加迭代器(使用 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;
    }
}

这篇关于您可以在迭代时从 std::list 中删除元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆