Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a std::vector with default constructor

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?

like image 493
Himadri Choudhury Avatar asked Mar 14 '11 04:03

Himadri Choudhury


2 Answers

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) { }
} 
like image 110
James McNellis Avatar answered Sep 30 '22 15:09

James McNellis


class myclass {
   std::vector<whatever> elements;
public:
   myclass() : elements(N) {}
};
like image 35
Jerry Coffin Avatar answered Sep 30 '22 15:09

Jerry Coffin