Skip to content
C++ Basics: Separate Vector Capacity from Its Element Count

C++ Basics: Separate Vector Capacity from Its Element Count

November 2, 2026

Reserving storage does not create vector elements. Compare reserve with resize before deciding whether indexing is valid.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and its standard-library headers, and make g++ available on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as vector-reserve-resize-demo.cpp:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> readings;
    readings.reserve(8);
    std::cout << std::boolalpha;
    std::cout << "After reserve: size=" << readings.size()
              << "; room for eight=" << (readings.capacity() >= 8) << '\n';
    readings.resize(3, 7);
    readings.at(1) = 9;
    std::cout << "After resize: size=" << readings.size() << "; values:";
    for (const int reading : readings) {
        std::cout << ' ' << reading;
    }
    std::cout << '\n';
}

Compile and run it. The && prevents execution if compilation fails:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic vector-reserve-resize-demo.cpp -o vector-reserve-resize-demo &&
./vector-reserve-resize-demo

Observed output:

After reserve: size=0; room for eight=true
After resize: size=3; values: 7 9 7

Read the result

reserve(8) leaves size() at zero while ensuring room for at least eight elements. resize(3, 7) creates three elements initialized to seven. Only then does at(1) refer to an existing element. The example checks a capacity lower bound instead of assuming an exact allocation size.

Apply it carefully

Never index reserved-but-unconstructed elements. Valid element indexes are below size(), not capacity(). Reallocation invalidates existing pointers, references and iterators; reserve may itself reallocate. Shrinking with resize removes elements but does not promise to reduce capacity.

The C++ working draft documents the relevant container behavior. The example uses only features available in C++20, even though the linked draft may include later additions.

Clean up

Remove only the source and executable created here, then remove the empty practice directory:

rm -- vector-reserve-resize-demo.cpp vector-reserve-resize-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on