【问题标题】:Array inside array in c++ similar to the list inside list in pythonc++中的数组内的数组类似于python中的列表内的列表
【发布时间】:2015-07-15 02:18:11
【问题描述】:

如何在 c++ 中的数组中定义一个数组,类似于 python 在列表中轻松定义一个列表,如

测试 = [[1,2,3], [4,5,6]]

【问题讨论】:

  • 也许this 可以帮到你一点。
  • 这取决于您希望它与列表列表的相似程度。

标签: python c++ arrays list


【解决方案1】:

考虑这些可能性:

auto test = { { 1, 2, 3 }, { 4, 5, 6 } };

这会将测试创建为包含两个 std::initializer_list 实例的 std::initializer_list

std::vector<std::vector<int>> test{ { 1, 2, 3 }, { 4, 5, 6 } };

创建一个向量向量。

std::vector<std::array<int, 3>> test{ { 1, 2, 3 }, { 4, 5, 6 } };

创建一个固定大小数组的向量。

std::array<std::array<int, 3>, 2> test{ { 1, 2, 3 }, { 4, 5, 6 } };

创建一个固定大小的数组(大小为 2),每个数组包含两个大小为 3 的固定大小的数组。

【讨论】:

    【解决方案2】:
    #include <vector>
    using namespace std;
    
    vector<vector<int>> test = { {1, 2, 3}, {4, 5, 6} };
    

    您当然会发现打字多了一些。这是因为 c++ 要求您更明确地了解您正在使用的容器的实际属性。那是因为 c++ 正在努力确保你做你想做的事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-19
      • 2011-02-18
      • 2022-06-15
      • 2021-08-29
      • 1970-01-01
      • 2020-09-29
      • 2014-06-23
      • 2019-10-09
      相关资源
      最近更新 更多