How do I properly and easily initialize an instance of a class that contains a std::vector of some other class that in itself contains some data.
I understand that it is really hard to explain it in words, so I will instead write a piece of code that does not work, but it captures my intention.
#include <vector>
struct Point
{
float x, y;
};
struct Triangle
{
Point points[3];
};
struct Geometry
{
std::vector<Triangle> triangles;
};
int main()
{
Geometry instance
{
{{0,0}, {6, 0}, {3, 3}},
{{5,2}, {6, 6}, {7, 3}}
};
return 0;
}
This code does not work. Clang returns an error -
excess elements in struct initializer
I can not figure out why it is giving me this error.
I imagine that I can initialize
std::vector of Triangles,Points,floats within each Point object.How would I go about properly initializing an instance of Geometry class with some values without writing too much code using the initializer brackets?
If you have alternatives, then I am open to considering them.
You need 2 pairs of additional braces for this to work:
Geometry instance
{{
{{{0,0}, {6, 0}, {3, 3}}},
{{{5,2}, {6, 6}, {7, 3}}}
}};
Here's a demo.
Explanations for all the braces:
Geometry instance
{ // for the Geometry object - instance
{ // for the vector member - triangles
{ // for the individual Triangle objects
{ // for the Point array - points[3]
{0,0}, {6, 0}, {3, 3}}}, // for the individual Points
{{{5,2}, {6, 6}, {7, 3}}}
}};
While I like using brace-init lists, when you have nesting this deep it might be more readable to spell out the types explicitly.
You can mention the triangles's type and provide a set of extra parentheses, then it should work
Geometry instance{
std::vector<Triangle> // explicitly mentioning the type
{
{ { {0,0}, {6, 0}, {3, 3}} },
{ { {0,0}, {6, 0}, {3, 3}} }
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With