Sign in to follow this  

removing item in std::list

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

Hello! I am converting a data structure from linked list pointers to std::list. Previously I had two functions for removing items in a linked list. The first function deleted the item using delete myPointer; and redirected the neighboring pointers to the correct positions. The second function didn't delete the actual data; it only redirected the remaining items in the list so they were pointing to each other. The data that was “removed” was still available in memory, never deleted. I am wondering if something similar is possible with std::list. I have Googled and searched cplusplus.com but haven’t found a graceful solution. Any help appreciated!

Share this post


Link to post
Share on other sites
The equivalent to the first is to use an iterator to the list element and calling list::erase() on that element. The equivalent to the second is to create a second empty list and using list::splice() to move the element from the first list to the second list.

Share this post


Link to post
Share on other sites
So a typical linked list has two 'pointers' you could be talking about.

The first is the Node pointer, the second is the data pointer. The second pointer -- the data pointer -- is sometimes replaced with a data member.

std::lists contain data members, which can (at your choice) be pointers. But std::list doesn't manage the memory held by the data pointer.

If your data is small and cheap to copy and doesn't have pointers pointing into it, you should just store an instance in the std::list, and before deleting or removing the stuff from the list, you make a copy and pass that copy around.

Otherwise, I'd recommend filling your std::list<> with boost::shared_ptr< your_data > (or std::tr1::shared_ptr<...>).

SiCrane's trick of putting the data into another std::list will work, but you will be forced to carry around the mini-list of one element to keep the list node alive. This could work in some circumstances, but it might get awkward if you want that data to have any serious lifetime. :)

Note that std::list's operator= and copy-construction is expensive (as it does a whole-list copy).

Share this post


Link to post
Share on other sites

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