简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM