Jump to content
  • Advertisement
Sign in to follow this  
utilae

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

This topic is 4997 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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
}

Share this post


Link to post
Share on other sites
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.]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 );
}




Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!