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 
    {}
};
user975989
  • 2,578
  • 1
  • 20
  • 38
user1899020
  • 13,167
  • 21
  • 79
  • 154

1 Answers1

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}}}
    {}
};
Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
  • I intuitively understand `{m00, m01}` for inner array, and `{{...}, {...}}` for outer, but why are the outermost braces needed? – eerorika Jun 09 '16 at 21:13
  • I think the answer is right. but why need 3 pairs of `{}`? If it is `vector>`, need 3 sets also? – user1899020 Jun 09 '16 at 21:13
  • @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}` – Revolver_Ocelot Jun 09 '16 at 21:18
  • @user1899020 http://stackoverflow.com/questions/18792731/can-we-omit-the-double-braces-for-stdarray-in-c14 – Bob__ Jun 09 '16 at 21:19
  • Maybe `initializer_list` is better? – Yves Jun 10 '16 at 07:10