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

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

    If you think of the std::list like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...

    std::list myList;
    
    int size = myList.size(); // The size needs to be saved to iterate through the whole thing
    
    for (int i = 0; i < size; ++i)
    {
        int val = myList.back()
        myList.pop_back() // dequeue
        if (val != 5)
        {
             myList.push_front(val) // enqueue if not 5
        }
    }
    

    myList will now only have numbers 1-4 and 6-10.

提交回复
热议问题