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

2
  • Maybe this could help you a bit. Commented May 5, 2015 at 11:16
  • It depends how similar to a list of lists you want it to be. Commented May 5, 2015 at 11:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.