Map with multiple keys in C++

11,755

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

Share:
11,755
danijar
Author by

danijar

Researcher aiming to build intelligent machines based on concepts of the human brain. Website · Twitter · Scholar · Github

Updated on June 04, 2022

Comments

  • danijar
    danijar almost 2 years

    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.