我需要一个数据结构来管理T
对象的整数ID(通常为std::string
)。它 应该支持获取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管理器已经在某个库中可用?
对于第一个问题,你似乎强制需要RAII。对于第二个问题,hash_map可能是另一个选项! – DumbCoder 2010-09-29 15:43:30