拥有对象并为其返回ID的数据结构

时间:2010-09-29 15:19:21

标签: c++ data-structures associative-array

我需要一个管理T个对象(通常为std::string)的整数ID的数据结构。它 应该支持获取某个对象的ID,反之亦然,获取某个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)

它还应拥有所有这些T个对象,因此在内部它会分配新对象,存储它们并在析构函数中删除它们。

有何评论?你会如何实现?

我在里面使用这两个容器;每个对象指针都存储在:

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

是否有其他可能有用的数据结构?或者整个对象ID管理器是否已在某些库中可用?

1 个答案:

答案 0 :(得分:1)

  

它也应该拥有所有那些T.   对象,所以内部分配   新对象,存储它们和删除   他们在析构函数中。

     

有何评论?你会如何实现?   是什么?

我会使用boost shared_ptr来管理对象。

  

是否还有其他数据结构   那可能有帮助吗?或者就是这样   对象ID管理器已经可用   一些图书馆?

检查此Stack Overflow线程:Using STL containers for multiple keys。我认为这是一个很好的替代解决方案,但是,老实说,我在很多项目中都使用了相同的方法。