Item in multiple lists
Posted
by Evan Teran
on Stack Overflow
See other posts from Stack Overflow
or by Evan Teran
Published on 2010-06-16T19:53:19Z
Indexed on
2010/06/16
20:12 UTC
Read the original article
Hit count: 223
So I have some legacy code which I would love to use more modern techniques. But I fear that given the way that things are designed, it is a non-option. The core issue is that often a node is in more than one list at a time. Something like this:
struct T {
T *next_1;
T *prev_1;
T *next_2;
T *prev_2;
int value;
};
this allows the core have a single object of type T
be allocated and inserted into 2 doubly linked lists, nice and efficient.
Obviously I could just have 2 std::list<T*>
's and just insert the object into both...but there is one thing which would be way less efficient...removal.
Often the code needs to "destroy" an object of type T
and this includes removing the element from all lists. This is nice because given a T*
the code can remove that object from all lists it exists in. With something like a std::list
I would need to search for the object to get an iterator, then remove that (I can't just pass around an iterator because it is in several lists).
Is there a nice c++-ish solution to this, or is the manually rolled way the best way? I have a feeling the manually rolled way is the answer, but I figured I'd ask.
© Stack Overflow or respective owner