Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item in std::list while leaving it allocated

I build a std::list of items (graph component structures) which are periodically merged together. The idea is if I discover a node connecting two components they become one single component and my list enumerates my components. Each component has a handle (in this case an std::list<component>::iterator) to its "parent" component which is set once it gets merged. This way to determine the component a particular node belongs to I walk up this chain.

In the end what I'm looking for is the operation on std::list which allows me to take an iterator of item N, and remove it from the list but without deallocating it: the structure of the rest of the list is modified in exactly the same way as removing it normally.

Preferably something less ugly than re-allocating the item, copying it from the list, and calling the real remove or erase.

Perhaps I can accomplish it with splice. I'd need to splice the elements to be removed into a "junk" list, don't I?

like image 450
Steven Lu Avatar asked Dec 20 '12 06:12

Steven Lu


1 Answers

You can do this with splice. For example, move *it to junk list:

junk.splice(junk.begin(),comp_list,it);

You can also add move-ctor to component. Then, before erasing from list move contents to tmp var, something like this:

component  tmp(*it);
li.erase(it);

Also suggestion of Fomin Arseniy to use list of pointers to components (or std::shared_ptr) is good too.

like image 162
Leonid Volnitsky Avatar answered Nov 09 '22 22:11

Leonid Volnitsky