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

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

    I have sumup it, here is the three method with example:

    1. using while loop

    list<int> lst{4, 1, 2, 3, 5};
    
    auto it = lst.begin();
    while (it != lst.end()){
        if((*it % 2) == 1){
            it = lst.erase(it);// erase and go to next
        } else{
            ++it;  // go to next
        }
    }
    
    for(auto it:lst)cout<<it<<" ";
    cout<<endl;  //4 2
    

    2. using remove_if member funtion in list:

    list<int> lst{4, 1, 2, 3, 5};
    
    lst.remove_if([](int a){return a % 2 == 1;});
    
    for(auto it:lst)cout<<it<<" ";
    cout<<endl;  //4 2
    

    3. using std::remove_if funtion combining with erase member function:

    list<int> lst{4, 1, 2, 3, 5};
    
    lst.erase(std::remove_if(lst.begin(), lst.end(), [](int a){
        return a % 2 == 1;
    }), lst.end());
    
    for(auto it:lst)cout<<it<<" ";
    cout<<endl;  //4 2
    

    4. using for loop , should note update the iterator:

    list<int> lst{4, 1, 2, 3, 5};
    
    for(auto it = lst.begin(); it != lst.end();++it){
        if ((*it % 2) == 1){
            it = lst.erase(it);  erase and go to next(erase will return the next iterator)
            --it;  // as it will be add again in for, so we go back one step
        }
    }
    
    for(auto it:lst)cout<<it<<" ";
    cout<<endl;  //4 2 
    
    0 讨论(0)
提交回复
热议问题