Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing array of std::vector in constructor init list

Usually when writing a constructor I try to initialize as many class members as possible in the member initialization list, including containers such as std::vector.

class MyClass
{
  protected:
  std::vector<int> myvector;

  public:
  MyClass() : myvector(500, -1) {}
}

For technical reasons, I now need to split this into an array of vectors.

class MyClass
{
  protected:
  std::vector<int> myvector[3];

  public:
  MyClass() : myvector[0](500, -1), myvector[1](250, -1), myvector[2](250, -1) {}
}

Turns out, I cannot initialize the array of vectors this way. What am I doing wrong? Or is this just not possible?

Of course I can still do this in the body of the ctor using assign, but I'd prefer to do it in the member init list.

like image 999
marcbf Avatar asked Nov 14 '25 12:11

marcbf


1 Answers

You should initialize the whole array, but not every element. The correct syntax to initialize the array should be

MyClass() : myvector {std::vector<int>(500, -1), std::vector<int>(250, -1), std::vector<int>(250, -1)} {}
like image 168
songyuanyao Avatar answered Nov 17 '25 08:11

songyuanyao



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!