0

How to initialize an array easily in the constructor? For example

class A
{
    array<array<int, 2>, 2> m;
    A(int m00, int m01, int m10, int m11)
       : m {m00, m01, m10, m11} // ??? how to list here 
    {}
};
1
  • 1
    It works as is if you fix the variable typos. Commented Jun 9, 2016 at 21:07

1 Answer 1

3
class A
{
    std::array<std::array<int, 2>, 2> m;
    A(int m00, int m01, int m10, int m11)
       : m {{{m00, m01}, {m10, m11}}}
    {}
};
Sign up to request clarification or add additional context in comments.

5 Comments

I intuitively understand {m00, m01} for inner array, and {{...}, {...}} for outer, but why are the outermost braces needed?
I think the answer is right. but why need 3 pairs of {}? If it is vector<vector<int>>, need 3 sets also?
@user1899020 In short, because array is an aggregate. Because inner type is an aggregate itself, you actually can drop all braces, except outer ones: m{m00, m01, m10, m11}
Maybe initializer_list is better?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.