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

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

    Iterating backwards avoids the effect of erasing an element on the remaining elements to be traversed:

    typedef list list_t;
    for ( list_t::iterator it = items.end() ; it != items.begin() ; ) {
        --it;
        bool remove = 
        if ( remove ) {
            items.erase( it );
        }
    }
    

    PS: see this, e.g., regarding backward iteration.

    PS2: I did not thoroughly tested if it handles well erasing elements at the ends.

提交回复
热议问题