vector::resize() vs vector::reserve() in C++ – Differences

This tutorial will show how vector::resize() differs from vector::reserve() in C++.

There are basically two main concepts regarding the space of vectors: size and capacity.

The capacity is always either greater or equal to the size. Whenever an element is added to the vector, the size of the vector increases and capacity remains the same unless adding the new element violates the rule of capacity being greater or equal to size. To increase the capacity we have to create a new buffer, copy old values to the new buffer, then remove the old buffer.

Let’s understand how vector::resize() and vector::reserve() work and how they are different from each other.

vector::resize()

The storage of vectors is maintained by the containers. The resize() function changes the content of the containers by inserting or deleting the elements from it.

Syntax:

vectorname.resize(int n, int value)
  • If the value of n is less than the size of the vector and the elements are deleted from the vector.
  • If n is more than the size of the vector then extra elements are added at the end of the vector.

For example, if the given vector isĀ  v={10,12,14,16,18}

If we use v.resize(4), the result will be vector v={10,12,14,16}.

vector::reserve()

The reserve function helps the user to change the capacity but not the size. It makes sure that the vector stores at least the specified number of elements without reallocating the memory. The main reason to use reserve is to prepare vectors about future potential size and to avoid repeated capacity increases.

Syntax:

vectorname.resize(int n)

The main reason to use reserve is to prepare vectors about future potential size and to avoid repeated capacity increases.

One response to “vector::resize() vs vector::reserve() in C++ – Differences”

  1. Jae says:

    A typo: the ‘Syntax’ code block for vector::reserve() needs to be corrected to “vectorname.reserve(int n)’

Leave a Reply

Your email address will not be published. Required fields are marked *