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

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

    The alternative for loop version to Kristo's answer.

    You lose some efficiency, you go backwards and then forward again when deleting but in exchange for the extra iterator increment you can have the iterator declared in the loop scope and the code looking a bit cleaner. What to choose depends on priorities of the moment.

    The answer was totally out of time, I know...

    typedef std::list::iterator item_iterator;
    
    for(item_iterator i = items.begin(); i != items.end(); ++i)
    {
        bool isActive = (*i)->update();
    
        if (!isActive)
        {
            items.erase(i--); 
        }
        else
        {
            other_code_involving(*i);
        }
    }
    

提交回复
热议问题