removing item in std::list

Started by
3 comments, last by O-san 14 years, 10 months ago
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!
Advertisement
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.
Thank you, I will try it out straight away!
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).
It works great, thanks a lot!

This topic is closed to new replies.

Advertisement