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.
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)} {}
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