I always use resize() because I cannot use reserve as it gives error: vector subscript out of range. As I\'ve read info about the differences of resize() and reserve(), I sa
A vector has a capacity (as returned by capacity()
and a size (as returned by size()
. The first states how many elements a vector can hold, the second how many he does currently hold.
resize
changes the size, reserve
only changes the capacity
.
See also the resize and reserve documentation.
As for the use cases:
Let's say you know beforehand how many elements you want to put into your vector
, but you don't want to initialize them - that's the use case for reserve. Let's say your vector was empty before; then, directly after reserve()
, before doing any insert
or push_back
, you can, of course, not directly access as many elements as you reserved space for - that would trigger the mentioned error (subscript out of range) - since the elements you are trying to access are not yet initialized; the size
is still 0. So the vector is still empty; but if you choose the reserved capacity in such a way that it's higher or equal to the maximum size your vector will get, you are avoiding expensive reallocations; and at the same time you will also avoid the (in some cases expensive) initialization of each vector element that resize would do.
With resize
, on the other hand, you say: Make the vector hold as many elements as I gave as an argument; initialize those whose indices are exceeding the old size, or remove the ones exceeding the given new size.
Note that reserve
will never affect the elements currently in the vector (except their storage location if reallocation is needed - but not their values or their number)! Meaning that if the size of a vector is currently greater than what you pass to a call to the reserve function on that same vector, reserve will just do nothing.
See also the answer to this question: Choice between vector::resize() and vector::reserve()