Map with multiple keys in C++

一世执手 提交于 2019-12-10 14:51:43

问题


I want to store data by both, their name and their index. In other words, I want to map string names to objects and also give them a custom order.

What I came up with first is a std::vector of pairs of the string key and the object. The order was given by the position in the vector.

std::vector<std::pair<std::string, object> >

But this approach seems to be suboptimal since it doesn't automatically check for the uniqueness of string names. Moreover it feels wrong to group the objects by their order first, because logically their first order distinction is the name.

I need a data structure that allows access by both name and index.

std::magic<std::string, unsigned int, object> collection;

// access by either string or unsigned int key
collection.insert("name", 42, new object());
collection["name"]
collection[42]

Is there a data structure for this use case already? If not, how can I put one together, preferably using the standard library? Also I would like a way to insert new elements at the position after a given element without moving all further elements around.


回答1:


Boost provides a set of containers just for this purpose, see: boost::multiindex



来源:https://stackoverflow.com/questions/15854071/map-with-multiple-keys-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!