list<Object*>::iterator itObjects;
for (itObjects=lstObjectList.begin();itObjects!=lstObjectList.end();itObjects++)
{
if((*itObjects)->sFilename==sFilename)
{
//remove object from list and delete object
lstObjectList.erase(itObjects);
}
removing and deleting an object in a linked list *solved*
Hi, I have a list of objects (std list). I want to go through the list using an iterator and stop when a condition is met. Then I want to remove that object from the list and delete the object (pointed to by the iterator). I am using erase, which removes the object from the list, but does it still have to be deleted or something, code below:
[Edited by - utilae on February 12, 2005 7:41:37 PM]
1) Yes. STL containers do not own the objects they contain.
2) If you call erase, the iterator is invalidated, thus you cannot increment. Use the return value from erase instead.
2) If you call erase, the iterator is invalidated, thus you cannot increment. Use the return value from erase instead.
list<Object*>::iterator itObjects = lstObjectList.begin();while( itObjects!=lstObjectList.end() ){ if((*itObjects)->sFilename==sFilename) { delete *itObjects; // or delete[] *itObjects; if you used new[] itObjects = lstObjectList.erase(itObjects); } else ++itObjects}
You must delete the memory associated with the pointer yourself. In this case I think you could just add the line:
delete *itObjects;
Before:
lstObjectList.erase(itObjects);
[Edit: Oops, beaten. Plus, forgot to mention the invalidated iterator.]
delete *itObjects;
Before:
lstObjectList.erase(itObjects);
[Edit: Oops, beaten. Plus, forgot to mention the invalidated iterator.]
Quote:Original post by iMalc
Couldn't some higher level method like "remove_if" be more appropriate here?
Not unless you're using smart pointers.
You need to make sure that you increment your iterator before you remove it from the list (is it remove or erase? or both?). The STL seems to have a flaw (well; not sure about STLport, but all that I've used) in this portion and it's always a pain in the ass. An example:
for(list<type>::iterator it=list.begin(); it != list.end(); it++) { list<type>::iterator me = it; list.erase( me );}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement