Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Remove Objects in List at Loop

Tags:

c++

stl

How can i delete all objects which are works finished

I using the following code but get list iterator not incrementable

How can I remove it without deleting it

list<A*> myList;
for(list<A*>::iterator it = myList.begin(); it !=myList.end(); ++it ){
    (*it )->DoSomething();
    if((*it )->WorksFnished()){
        //myList.erase(it );    <- It's works but I get exception after the loop
        //myList.remove(*it );  <- It's works but I get exception after the loop
    }
}
like image 957
Abdullah Avatar asked Feb 28 '26 04:02

Abdullah


1 Answers

erase returns an iterator

list<A*> myList;
list<A*>::iterator it = myList.begin();
while( it != myList.end() ) {
    (*it)->DoSomething();
    if( (*it)->WorksFnished() ) {
        it = myList.erase(it);
    } else {
        ++it;
    }
}
like image 179
sp2danny Avatar answered Mar 02 '26 17:03

sp2danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!