开发者

Data structure that owns objects and returns IDs for them

开发者 https://www.devze.com 2023-01-18 06:13 出处:网络
I need a data structure that manages integer IDs for T objects (typically std::string). It should support getting the ID for some object and, vice versa, get the object for some ID:

I need a data structure that manages integer IDs for T objects (typically std::string). It should support getting the ID for some object and, vice versa, get the object for some ID:

// if object not seen before: copies and stores object and returns
// new ID, otherwise just returns its ID
int Add(const T& obj);

// if obj not found: returns some specified `NotFound` ID,
// otherwise just returns its ID
int GetId(const T& obj);

// if id not contained: throws exception, 
// otherwise returns associated object
const T& GetObj(int id)

It should also own all those T objects, so internally it allocates new objects, stores them and deletes them in the destructor.

Any comments? How开发者_如何转开发 would you implement that?

I am using these two containers inside; every object pointer is stored in both:

// quickly retrieve the ID
std::map<const T*, int, CompareByValue> Obj2IdMap;
// quickly retrieve the object, given an ID
std::vector<const T*> Id2ObjMap;

Are there any other data structures that might help? Or is this whole object ID manager already available in some library?


It should also own all those T objects, so internally it allocates new objects, stores them and deletes them in the destructor.

Any comments? How would you implement that?

I would use boost shared_ptr to manage the objects.

Are there any other data structures that might help? Or is this whole object ID manager already available in some library?

Check this Stack Overflow thread: Using STL containers for multiple keys. I think thats a good alternative solution for your problem although, to be honest, I have used your very same approach in lots of projects too.

0

精彩评论

暂无评论...
验证码 换一张
取 消