By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,897 Members | 1,969 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,897 IT Pros & Developers. It's quick & easy.

managing objects in std::list

P: n/a
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.
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

Glen Able wrote:
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

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.