Have a map with keys consisting of different types in C++

后端 未结 3 1110
别那么骄傲
别那么骄傲 2021-01-21 20:46

I currently am using a map in C++ and have a couple of values that are ints and booleans, though the majority of them are strings. I know in Java I could do something like this:

相关标签:
3条回答
  • 2021-01-21 21:08

    "but is there an Object equivalent in C++??"

    No, there isn't such thing in standard C++. c++-cli may provide something similar perhaps.

    "If not, is there any way I could properly have keys being a string, int, or boolean?"

    There's stuff like boost::variant or boost::any, but I'm not sure, if you could use them as a key in a std::map.

    Sounds a bit you're asking for a XY-Problem. Explain your actual use case please.

    0 讨论(0)
  • 2021-01-21 21:11

    I don't know of a way you could have a std::map with keys that can be multiple types using the stdlib out of the box.

    Boost has a variant type that functions more or less like what you want.

    typedef boost::variant<std::string, int, bool> key_type;
    std::map<key_type, Object*> mapvar
    

    This map will only accept keys that are defined in your chosen key_type, so you could not also use, say, a std::wstring as a key without explicitly declaring it. This would be the advantage of using a variant over any. The latter might happily eat whatever type you send its way, while the former will give you a compile time error.

    If you are going to use a boost::variant as your key then you need to read the boost documentation and look into what is involved in constructing variant objects and whether or not they have sorting pre-defined. std::map is built on operator< (unless you template it on some other sorting functor) so you'll need to make sure a working definition for your variant type is provided by either the library or yourself.

    --

    Why do you want to have such a map in the first place?

    0 讨论(0)
  • 2021-01-21 21:32

    You can have several different maps, and hide the lookup in overloaded functions:

    std::map<int, Object>           map_int;
    std::map<std::string, Object>   map_string;
    
    Object& lookup(int Key)
    { return map_int[Key]; }
    
    Object& lookup(std::string Key)
    { return map_string[Key]; }
    

    Now all your lookups kan be done with lookup(key).

    0 讨论(0)
提交回复
热议问题