Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with multiple keys in C++

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.

like image 324
danijar Avatar asked Apr 06 '13 17:04

danijar


1 Answers

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

like image 70
Chad Avatar answered Sep 29 '22 05:09

Chad