Reputation: 55
-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.
v.size() == n
Upvotes: 0
Views: 133
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