Initializing a std::vector with default constructor

27,955

Solution 1

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

Solution 2

class myclass {
   std::vector<whatever> elements;
public:
   myclass() : elements(N) {}
};

Solution 3

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.

Share:
27,955
Himadri Choudhury
Author by

Himadri Choudhury

Trying to be a better programmer.

Updated on July 23, 2022

Comments

  • Himadri Choudhury
    Himadri Choudhury almost 2 years

    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?