managing objects in std::list

G

Glen Able

Hi,

I have a collection of lists, something like this:

std::list<Obj*> lists[10];

Now I add an Obj to one of the lists:

Obj* gary;
lists[3].push_front(gary);


Then later on, the Obj wants to remove itself from whichever list it was put
in (it's only allowed to be in one list). What's the best way to do this
efficiently?

My best idea is: when adding an Obj to a list, the Obj has to store the
address of the list, and also an iterator to the current start of the list
(i.e. where it's just been added). Later it can use these to remove itself.

Anyone have anything smarter than this?

ta,
G.A.
 
M

msalters

Glen said:
Hi,

I have a collection of lists, something like this:

std::list<Obj*> lists[10];

Now I add an Obj to one of the lists:

Obj* gary;
lists[3].push_front(gary);

Actually, you have an array of lists of Obj pointers, and you
try to add an unitialized pointer to that list. That's undefined
behavior, and anything thath happens is Your Fault (TM).
Then later on, the Obj wants to remove itself from whichever list it was put
in (it's only allowed to be in one list). What's the best way to do this
efficiently?

This sounds like a bad design. There are a number of problems with this
approach: Your list doesn't contain objects but only the pointers. List
assumes it holds objects by value, which will work for pointers but
I'm afraid your objects don't have proper value semantics. You have no
obvious way to enforce your containment constraint.

The best way would be to wrap your Objects and the lists in a class.
(private members). Outside the class, you can only get an Object&.
The wrapper class is the one removing Objects from its own lists, and
thus enforces the association between Objects and lists.
My best idea is: when adding an Obj to a list, the Obj has to store the
address of the list, and also an iterator to the current start of the list
(i.e. where it's just been added). Later it can use these to remove
itself.

Won't work, you can move elements between identical lists (splice). In
that case, an Object may end up in a different list.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,654
Latest member
LannySinge

Latest Threads

Top