Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer-list on 3 levels

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

  • the std::vector of Triangles,
  • then the array of Points,
  • then the two 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.

like image 883
ManOfRuskie Avatar asked Mar 28 '26 09:03

ManOfRuskie


2 Answers

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.

like image 137
cigien Avatar answered Mar 29 '26 23:03

cigien


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}} }
         }
};
like image 20
JeJo Avatar answered Mar 30 '26 01:03

JeJo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!