Nguyễn Văn Dũng
Nguyễn Văn Dũng

Reputation: 55

Should we create vector with fixed size and then push_back if need more or not initialize

-As we known, push_back will sometime need cost than O(1). So should we create vector like:

std::vector<T> v(n); // With n is number we guess the instances T will be used.  

Upvotes: 0

Views: 133

Answers (1)

TartanLlama
TartanLlama

Reputation: 65630

The code which you posted will default-construct n instances of T, not just allocate memory for them. Depending on what T is, this might be a lot of unnecessary overhead. If you want to just allocate the memory so that the vector doesn't need to be resized as much, you should use reserve:

std::vector<T> v;
v.reserve(n);

Upvotes: 6

Related Questions