I have a class field which is a std::vector. I know how many elements I want this vector to contain: N. How do I initialize the vector with N elements?
std::vector
has a constructor declared as:
vector(size_type N, const T& x = T());
You can use it to construct the std::vector
containing N
copies of x
. The default value for x
is a value initialized T
(if T
is a class type with a default constructor then value initialization is default construction).
It's straightforward to initialize a std::vector
data member using this constructor:
struct S {
std::vector<int> x;
S() : x(15) { }
}
class myclass {
std::vector<whatever> elements;
public:
myclass() : elements(N) {}
};
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