问题描述:

How can I define an array inside an array in c++ similar to the python ease of defining of a list inside a list like

test = [[1,2,3], [4,5,6]]

网友答案:
#include <vector>
using namespace std;

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

You will of course observe that there is a bit more typing. That's because c++ demands that you're more explicit about the actual properties of the container you're using. And that's because c++ is striving to ensure that you do exactly what you want to do.

网友答案:

Consider these possibilities:

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

This creates test as a std::initializer_list that contains two std::initializer_list instances.

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

creates a vector of vectors.

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

creates a vector of fixed size arrays.

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

creates a fixed size array (of size 2), containing two fixed size arrays of size 3, each.

相关阅读:
Top