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

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

    Removal invalidates only the iterators that point to the elements that are removed.

    So in this case after removing *i , i is invalidated and you cannot do increment on it.

    What you can do is first save the iterator of element that is to be removed , then increment the iterator and then remove the saved one.

提交回复
热议问题