Sign in to follow this  

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

This topic is 4689 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
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

This topic is 4689 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this