【发布时间】:2015-07-15 02:18:11
【问题描述】:
如何在 c++ 中的数组中定义一个数组,类似于 python 在列表中轻松定义一个列表,如
测试 = [[1,2,3], [4,5,6]]
【问题讨论】:
-
也许this 可以帮到你一点。
-
这取决于您希望它与列表列表的相似程度。
如何在 c++ 中的数组中定义一个数组,类似于 python 在列表中轻松定义一个列表,如
测试 = [[1,2,3], [4,5,6]]
【问题讨论】:
考虑这些可能性:
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 的固定大小的数组。
【讨论】:
#include <vector>
using namespace std;
vector<vector<int>> test = { {1, 2, 3}, {4, 5, 6} };
您当然会发现打字多了一些。这是因为 c++ 要求您更明确地了解您正在使用的容器的实际属性。那是因为 c++ 正在努力确保你做你想做的事。
【讨论】: