0

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

saurabh
  • 293
  • 2
  • 7
  • 19

2 Answers2

4

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.

utnapistim
  • 26,809
  • 3
  • 46
  • 82
3
#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.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142