Can you remove elements from a std::list while iterating through it?

后端 未结 13 1012
长情又很酷
长情又很酷 2020-11-22 06:30

I\'ve got code that looks like this:

for (std::list::iterator i=items.begin();i!=items.end();i++)
{
    bool isActive = (*i)->update();
    /         


        
13条回答
  •  自闭症患者
    2020-11-22 06:56

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

提交回复
热议问题