我需要一個數據結構來管理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