I've read in this post that the initial capacity of a std::vector
couldn't be controlled by its constructor. The best way to set it, if you know its size will be constant at runtime, seems then to be:
const int size;
std::vector<T> v;
v.reserve(size);
But, since T
is a big class, I'm happy to use the initialization argument of the constructor std::vector<T> v(size, T());
. What is then the best way to allocate only the memory I need without having to manually iterate over the elements to initialize them?
std::vector<T> v;
v.reserve(size);
for(T t : v) t = T(); // `has to call T::operator= (that may not even be defined)
or
std::vector<T> v(size, T()); // may allocate more memory than I need..
v.shrink_to_fit(); // ..then deallocate it immediately (pointless)
What would be the closest to my ideal:
std::vector<T> v(size, T(), /*capacity =*/ size);
[EDIT]: It turns out from your answers that what I need more exactly is v
to be filled with size
instances of T
, each build with T
's default constructor, and not copied. How can I do since I can't use an initializer list when size
isn't known at compile time?
Bonus: By the way, why is there no way choosing the initial capacity of a vector?