2010-09-29 106 views
0

我需要一個數據結構來管理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管理器已經在某個庫中可用?

+0

對於第一個問題,你似乎強制需要RAII。對於第二個問題,hash_map可能是另一個選項! – DumbCoder 2010-09-29 15:43:30

回答

1

還應該擁有所有那些牛逼 對象,因此它在內部分配 新的對象,將它們存儲並在析構函數刪除 他們。

有何評論?你將如何實施 ?

我會用boost shared_ptr來管理對象。

是否還有其他數據結構 可能有幫助?或者是整個 對象ID管理器已經在 某些庫中可用?

檢查此堆棧溢出線程:Using STL containers for multiple keys。我認爲這是您的問題的一個很好的替代解決方案,但老實說,我也在很多項目中使用了同樣的方法。

+0

他們推薦Boost.MultiIndex。這是有道理的(雖然它看起來有點嚇人......)。 – Frank 2010-09-29 22:47:40