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

后端 未结 13 852
长情又很酷
长情又很酷 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:48

    Here's an example using a for loop that iterates the list and increments or revalidates the iterator in the event of an item being removed during traversal of the list.

    for(auto i = items.begin(); i != items.end();)
    {
        if(bool isActive = (*i)->update())
        {
            other_code_involving(*i);
            ++i;
    
        }
        else
        {
            i = items.erase(i);
    
        }
    
    }
    
    items.remove_if(CheckItemNotActive);
    

提交回复
热议问题