I've created a function to calculate a 3x3 determinant. This is its prototype:
double threeDet(array<array<double, 3>, 3> det);
I've used class array because it seems safer than traditional arrays. I wanted to test the function, so I called it:
threeDet({ {2, -3, 1}, {2, 0, -1}, {1, 4, 5} });
However, it raises an error of "too many initializers"
This has also happened when I changed the function to:
double threeDet(double det[][3]);
Initializing the array first raises the same error:
array<array<double, 3>, 3> det({ {2, -3, 1}, {2, 0, -1}, {1, 4, 5} });
threeDet(det);
the only thing that worked is to change the function to the second version, and initialize the array separately:
double det[3][3] = { {2, -3, 1}, {2, 0, -1}, {1, 4, 5} };
threeDet(det);
I wonder what am I missing, and if there is a way to initialize that I'm missing.
CodePudding user response:
There's a good rule of thumb to follow until one becomes comfortable with braced initialization lists, and how they work: when a std::array
is involved, double-up the braces:
threeDet({{ {{2, -3, 1}}, {{2, 0, -1}}, {{1, 4, 5}} }});
A std::array
is an aggregate object containing one class member: the array itself. So:
The outer set of braces construct the
std::array
.The inner set of braces construct its class member array.
Now, once you get passed that part, you have a pair of braces that construct each value in the array. Well, each such value is also a std::array
, so you need to drop in another pair of braces to initialize its array class member.