Walking thru a STL list and remove element at the same time?

A

Allerdyce.John

In STL list, is it safe to do this:

list<A> aList; //private attribute of MyClass


void MyClass:: aMethod() {
list<A>::Iterator iter;

for ( iter = aList.begin() ; iter != aList.end() ; iter++) {
A a = (*iter);

if ( check(a) ) {

aList.erase (iter); // is that okay?

}
}

}

Thank you.
 
R

roberts.noah

In STL list, is it safe to do this:

list<A> aList; //private attribute of MyClass


void MyClass:: aMethod() {
list<A>::Iterator iter;

for ( iter = aList.begin() ; iter != aList.end() ; iter++) {
A a = (*iter);

if ( check(a) ) {

aList.erase (iter); // is that okay?

Change to iter = aList.erase(iter);
 
E

E. Mark Ping

Change to iter = aList.erase(iter);

Which will get you into trouble when you get to iter++ at the for
loop.

The full approach is:

list<A> aList; //private attribute of MyClass

void MyClass:: aMethod() {
list<A>::Iterator iter;

//note no increment in the third clause of the for loop
for ( iter = aList.begin() ; iter != aList.end() ; ) {
A a = (*iter);

if ( check(a) ) {
iter = aList.erase (iter); // is that okay?
} else {
++iter;
}
}

}


Or you can simply use remove_if.
 
D

Daniel T.

In STL list, is it safe to do this:

list<A> aList; //private attribute of MyClass


void MyClass:: aMethod() {
list<A>::Iterator iter;

for ( iter = aList.begin() ; iter != aList.end() ;
iter++) {
A a = (*iter);

if ( check(a) ) {

aList.erase (iter); // is that okay?

}
}

}

Thank you.

aList.erase(aList.begin(),
remove_if(aList.begin(), aList.end(), &check ));

But don't do the above if aList contains pointers and you need to delete
the objects before removal. Of course, if that's the case then you
should probably wrap them in a smart pointer.
 
R

Richard Herring

aList.erase(aList.begin(),
remove_if(aList.begin(), aList.end(), &check ));

The remove_if algorithm may have to copy many instances of A, which
could potentially be quite expensive. std::list provides a more
efficient alternative:

aList.remove_if(check);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top