问题
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