Initializing a std::vector with default constructor
I have a class field which is a std::vector. I know how ma开发者_开发知识库ny 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) {}
};
All the constructors that allow you to specify a size also invoke the element's constructor. If efficiency is paramount, you can use the reserve()
member function to reserve the size. This does not actually create any elements, so it is more efficient. In most cases, though, supplying the size through the vector constructor is just fine.
精彩评论