C ++ Equivalent to Python List of Dictionaries?

I have a list of Python dictionaries containing information about the individual layers of a neural network. Each dictionary can have any number of entries, including more dictionaries.

layer_config = [
 {'conv_layer': {
     'filter_size' : 5,
     'stride' : 1,
     'num_filters' : 20}},
 {'pool_layer': {
     'poolsize' : (2,2)}},
 {'fc_layer': {
     'num_output' : 30}},
 {'final_layer': {
     'num_classes' : 10}}
]

      

I am converting a program to C ++ and must find a way to arrange this information in a similar way. Are nested C ++ maps the best way to do this, or is there another data structure that might be a better alternative?

+3


source to share


2 answers


In C ++, to use nested maps for this problem, each map must be of the same type. If you created a map of maps, submars would need to store the same type of information (e.g. strings and ints), and it seems that you have different information contained in your dictionary depending on the key (i.e. you have a pair (2,2) with the key "pool" where there are integers elsewhere). The C ++ way to do this might be to create a struct or class that contains this information. For example, you can create a four-card structure for your conv_layer, pool_layer, etc. From your example, it looks like your data structure only requires one map for conv_layer and many pairs for all other variables. If so, you can use something like this for your data structure:



struct layer_config{
        std::map<std::string, int> conv_layer;
        std::pair<std::string, std::pair<int, int>> pool_layer;
        std::pair<std::string, int> fc_layer;
        std::pair<std::string, int> final_layer;
};

      

+4


source


You can use a C ++ map, which is like a python dictionary, and a vector:

vector<map<string, map<string, int> > >neural_data;
map<string, map<string, int> >regular_data;
regular_data["conv_layer"]["filter_size"] = 5;
neural_data.push_back(regular_data);
cout << neural_data[0]["conv_layer"]["filter_size"]<< endl; 

      



Then you can loop over and assign the rest of your data.

+2


source







All Articles