Search code examples
c++dictionarycommand-lineboost-program-options

add key value pairs in program options


I need to load a map inside my program, with an integer key and a string value, like this:

1, oil
2, car
5, house

I want to load them using boost::program_options. I can see in the tutorial that I can load a vector from options with a syntax like this one:

int opt;
po::options_description desc("Allowed options");
desc.add_options()
    ("help", "produce help message")
    ("optimization", po::value<int>(&opt)->default_value(10), "optimization level")
    ("include-path,I", po::value< vector<string> >(), "include path")
    ("input-file", po::value< vector<string> >(), "input file");

then I can use program --input-file file1, --input-file file2 in order to create a vector with file1 and file2. What's the best way to implement a map from program options?

I can use for example a string and then splitting string in order to obtain values, like program --pair "1, oil" --pair "2, car" --pair "5, house", or I can separate them using program --key 1 --value oil --key 2 --value car --key 5 --value car.

I want to use something that can be written easily from both command line and configuration file. Which method is the best one?


Solution

  • I can use for example a string and then splitting string in order to obtain values, like program --pair "1, oil" --pair "2, car" --pair "5, house" ...

    I'd stick with the 1st option and read the std::vector<std::string> vector of strings. Afterwards you go through the natively parsed vector, split up the strings and fill your map.

    ... or I can separate them using program --key 1 --value oil --key 2 --value car --key 5 --value car

    I'm not sure this way would preserve the strong ordering you need.