Search code examples
pythonc++dictionarynestedhashmap

Nested maps in C++ with vectors of different types as values


I am trying to convert the following Python code into C++:

outer_dict = {}

outer_dict[0] = {}
outer_dict[0]["ints"] = [0]
outer_dict[0]["floats"] = [0.0]

outer_dict[0]["ints"].append(1)
outer_dict[0]["floats"].append(1.2)

outer_dict[1] = {}
outer_dict[1]["ints"] = [0]
outer_dict[1]["floats"] = [0.5]

Essentially, the data structure is a nested dictionary in python where the values of the inner dictionary are lists of different data types. The overall data structure looks as follows:

outer_dict 
{
  0: 
  {
    "ints": [0, 1]        // list of ints
    "floats": [0.0, 1.2]  // list of floats
  }
  1:
  {
    "ints": [0]          // list of ints
    "floats": [0.5]      // list of floats
  }
}

How can such a code be converted to C++?


Solution

  • As @Pepijn Kramer mentioned you can use a struct containing vectors of int and float -

    struct IntsAndFloats
    {
        std::vector<int> Ints;
        std::vector<float> Floats;
    };
    

    Then you can initialize it like this -

    std::vector<IntsAndFloats> outer_dict = {
        // 0 :
        {
            {0, 1}, // Ints
            {0.0, 1.2} // Floats
        },
        // 1 :
        {
            {0}, // Ints
            {0.5} // Floats
        }
    };
    

    See full code here