Best practice for storing an object in multiple containers

I want to keep the object in priority_queue

, and in unordered_map

. Is there a better way to do something like this? I considered storing objects in a separate container (say array

) and then discarding pointers to the other two containers.

I hesitate to do this because it would mean that I would have to write a few additional comparators to cope with the fact that the containers will store pointers rather than actual objects. In addition, there is additional work managing the ownership of objects that I don't want to deal with.

So, I'm wondering if there isn't an already established best way to do this?

+3


source to share


1 answer


You saw that you need to keep a reference (of some sort) to an object if you want one thing to appear in 2 places. While you once used a pointer, today is shared_ptr .

This wraps the pointer, so you don't need to manage lifetime ownership - the pointer will only be deleted when the shared_ptr's reference count drops to 0, i.e. when everyone who has a shared_ptr discards it. You are using the shared_ptr object as a real object, so it is easy to manage it in your containers.



If you don't have a C ++ 11 compiler, you can use the boost version (which comes with an example of storing shared_ptr objects in both a vector and a set)

+3


source







All Articles