Are extra curly brackets really required when initialize structures comparing with primitive types? It's kind of inconsistent design, can someone help explain?
1. array with primitive type e.g int can be initialized with:
struct<int, 3> i {1,2,3};
2. however, with struct Point (example below), seems need extra curly brackets:
I am not sure and this is more of a guess at the moment. If I am misunderstanding it someone will say so.
1 2 3 4 5 6
array<Point, 3> a
{ // <--- To initialize the whole
{ // <--- Maybe because each element is a struct?
{ 1, 1 }, { 2, 2 }, { 3, 3 } // <--- To initialize the 3 structs of each element of the array.
}
};
I'm with lastchance re use of array. Can't remember the last time I used it. And now there is span in C++20. begin()/end()/size() already work fine with c-style array in scope. And if you pass a c-style array to a function, use a template to get the size(s).
A std::vector can be constructed with an initializer list. So, a list of Point objects can be used herre.
The Array struct contains a Point[3] array. If you were creating a Point[3] on the stack, it would be: Point elem[3] = {{1, 2}, {3, 4}, {5, 6}};
Because you actually want to create an Array object which contains a Point[3], you need to create the Point[3] as PART of the Array creation.
To paraphrase @HandyAndy:
1 2 3 4 5 6
Array points2
{ // <--- To initialize the Array object
{ // <--- To initialize the elem[3] within the Array
{ 1, 1 }, { 2, 2 }, { 3, 3 } // <--- To initialize the 3 structs of each element of the array.
}
};
This issue with needing an extra set of braces when initializing a std::array has been around since the container was introduced in C++11. Other containers don't need them:
Which causes error in my VScode with message: too many initializer values
I get the same error with Visual Studio 2019 without the extra set of braces. A bit ironic when it really seems to mean there are not enough initializer values.
BTW, why are you returning 1 in main? Any non-zero return status 'tells the OS' the program didn't end successfully.