Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Python dictionary" functionality in C++?

In Python, one can define a dictionary like

a = {
    'a': 'hhh',
    'b': 123,
    'jfa': {'j': 1.5, 'r': 'string'}
    }

In C++11, I see that you can

std::map<std::string, int> a = {
  {"a", 1},
  {"hh", 4}
};

but really I'd like the values to differ in type (and particularly allow dictionaries as values). Is there an idiom or library that does allow for this? Is anything planned for the next standard?

like image 585
Nico Schlömer Avatar asked Oct 20 '22 04:10

Nico Schlömer


2 Answers

There currently is boost::variant (which allows a specific set of types to fit into an object) or boost::any which allows any type to be fit into the object. As far as I know both of them are being considered to be added to the standard library, but I'm more sure about any.

like image 156
Shoe Avatar answered Nov 03 '22 05:11

Shoe


You could consider Niels Lohmann’s excellent JSON for C++ library. Single header, permissive license, makes JSON a first class type.

Link here: https://github.com/nlohmann/json

Example:

nlohmann::json myDict = {
  {"a", 1},
  {"hh", 4}
}
like image 39
VorpalSword Avatar answered Nov 03 '22 05:11

VorpalSword