C++ 中以不同类型的向量作为值的嵌套映射

问题描述 投票:0回答:1

我正在尝试将以下Python代码转换为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]

本质上,数据结构是Python中的嵌套字典,其中内部字典的值是不同数据类型的列表。整体数据结构如下:

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
  }
}

这样的代码如何转换为C++?

python c++ dictionary nested hashmap
1个回答
0
投票

这样的东西应该有效:

#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    typedef std::map<std::string, std::vector<double>> InnerMap;
    std::map<int, InnerMap> outer_dict;

    outer_dict[0]["ints"] = std::vector<double>{0};
    outer_dict[0]["floats"] = std::vector<double>{0.0};

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

    outer_dict[1]["ints"] = std::vector<double>{0};
    outer_dict[1]["floats"] = std::vector<double>{0.5};

    return 0;
}

© www.soinside.com 2019 - 2024. All rights reserved.