C++ standard vector resize() function

From this site:

  • resize(): This lets you change the size of the vector to any size you want.
    • It will fill the underlying buffer with elements.
  • reserve(): This changes the capacity of the vector. Note that this doesn’t change the vector’s size, it just changes the size of the underlying buffer, to give more room for expansion of the buffer before the buffer has to be resized. Unlike calling resize(), this doesn’t change the behavior of the program, just the performance (Subsequent use of the reserved space will not incur a performance penalty for incremental reservations).
    • It will not limit the size of the buffer. If the buffer runs out of space it will automatically reallocate as needed.

enter image description here

The question I have is whether resize also works the same as in the capacity of the vector will only not increase? To add, would a combination of :

 std::vector<X> vector;
 vector.reserve(5);
 vector.resize(5);

make any sense? Is it redundant?

vector.reserve(5); Would be redundant in this case.

The goal here is to be able to overwrite values in the vector without having the vector allocate any extra space.

For this goal it depends on how you want to overwrite the values.

  • If you are planning to write directly by index, then you must use resize().
  • If you are using push_back(), then reserve() would be better so that you can avoid creating X twice.

Keep in mind that the algorithm used for the automatic reservation is implementation defined. See here for more regarding the performance aspect.


I don't know where you got your info about reserve, but it will reallocate if the number you pass to it is greater than the vector's current capacity, as reported by the capacity function.

As for resize, it is required to set the number of elements, and if there isn't enough space in the capacity, it will also require a reallocation.

As for your code snippet:

std::vector<X> vector;
vector.reserve(5);
vector.resize(5);

This might make sense if you want to allocate the minimum amount possible in order to store 5 elements. The reason I say that is because resize might allocate more in anticipation for more additions later on (to be clear, this can only happen if the requested size is greater than the capacity. resize will never cause a reallocation if the requested size <= capacity). reserve on the other hand, usually just allocates exactly enough. It is allowed to allocate more, but I have never seen an implementation which does that.


The main difference between them is that resize lets you change the size (either increase or decrease) while reserve only reserves memory from the system. Resize initialises allocated memory with either a call to default constructor or copy constructor based on form of the resize used.

Both may cause memory reallocation.