Initializing std :: vector with the default constructor

I have a class field that is std :: vector. I know how many elements I want this vector to contain: N. How to initialize a vector with N elements?

+4
source share
3 answers

std::vector has a constructor declared as:

vector(size_type N, const T& x = T());

You can use it to build std::vectorcontaining Ncopies x. The default value for xis the value initialized T(if it Tis a class type with a standard constructor, then the initialization of the value is the default).

Simple to initialize a data element std::vectorusing this constructor:

struct S {
    std::vector<int> x;
    S() : x(15) { }
} 
+6
class myclass {
   std::vector<whatever> elements;
public:
   myclass() : elements(N) {}
};
+7

All constructors that allow you to specify the size also call the element's constructor. If efficiency is paramount, you can use the member function reserve()to reserve size. In fact, this does not create any elements, so it is more efficient. However, in most cases, providing size through a vector constructor is just fine.

+1
source

All Articles