removing and deleting an object in a linked list *solved*

Started by
5 comments, last by bkt 19 years, 3 months ago
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:

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);
}


[Edited by - utilae on February 12, 2005 7:41:37 PM]

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

Advertisement
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.

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}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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.]
Couldn't some higher level method like "remove_if" be more appropriate here?
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thanks for, that helps heaps.

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

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 );}




-John "bKT" Bellone [homepage] [[email=j.bellone@flipsidesoftware.com]email[/email]]

This topic is closed to new replies.

Advertisement