Joon. P Joon. P - 1 year ago 99
C++ Question

C++11 Simplest way to store multiple data types for value(int and string) in map<key, value>?

I want to have a map that uses

  • string for key

  • int OR string for value

like this:

std::map<std::string, SOME TYPE> myMap;
myMap["first_key"] = 10;
myMap["second_key"] = "stringValue";

What is the SIMPLEST way to do such thing?

added) I am looking for solution that works in c++11

Answer Source

In c++17, you may use std::variant<int, std::string>, prior to this, you may use the one from boost:

using IntOrString = std::variant<int, std::string>;
std::map<std::string, IntOrString> myMap;
myMap["first_key"]  = 10;
myMap["second_key"] = "stringValue";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download