Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Equivalent of Python List of Dictionaries?

I have a Python list of dictionaries that contain information about 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 the program into C++ and need to find a way to organize this information in a similar manner. Are C++ nested maps the best way to accomplish this, or is there another data structure out there that might be a better alternative?

like image 976
nlhenderson17 Avatar asked Feb 05 '23 10:02

nlhenderson17


2 Answers

In C++, to use nested maps for this problem, each map would have to be of the same type. If you created a map of maps, the submaps would all have to hold the same type of information (like strings and ints), and it appears that you have different information being held in your dictionary depending on the key, (i.e you have a pair (2,2) at key "poolsize", where elsewhere you have integers). The C++ way to do this could be to create a struct or class which holds this information. For instance, you could create a struct with four maps for your conv_layer, pool_layer and so on. From your example, it looks like your data structure only needs one map for conv_layer, and a bunch of pairs for all of the other variables. If this is the case, you could 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;
};
like image 128
Jayson Boubin Avatar answered Feb 07 '23 02:02

Jayson Boubin


You can use a c++ map, which is similar to the 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; 

You can then loop through and assign the rest of your data

like image 31
Ajax1234 Avatar answered Feb 07 '23 00:02

Ajax1234