Library contents

C++ std::vector::reserve

Reserve capacity before appending readings to a vector that already contains a value.

A simple example

std::vector::reserve

  1. Start with An empty vector
  2. Do this Reserve room for three items
  3. Result Size 0, capacity at least 3
Allocation prepares storage. Elements are added separately.

Syntax

C++ syntax
readings.reserve(4)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Make room for more meter readings

A meter logger has one reading and expects several more. Reserve capacity before appending the next measurement and check that growing the buffer preserves the original reading.

Result12, 15
lesson.cpp
#include <vector>
#include <iostream>

int main() {
    std::vector<int> readings {12};
    readings.reserve(4);
    readings.push_back(15);
    std::cout << readings[0] << ", " << readings[1] << "\n";
    return 0;
}
Output
12, 15

The original twelve survives the capacity change. Appending fifteen then increases the size to two.

Advertisements

Grow a studio reading buffer

The sensor desk has six one-byte samples and expects four more. Plan enough storage for both batches before filling the buffer. What minimum capacity, in item slots, should be requested?

Given6 occupied + 4 incoming
Worked result10

Reserve a class roster buffer

A registration desk has ten records and expects a group of eight. Plan enough storage for both batches before filling the buffer. What minimum capacity, in item slots, should be requested?

Given10 occupied + 8 incoming
Worked result18

What to watch for

reserve changes capacity, not size. Reallocation can invalidate pointers and iterators.

Documentation for std::vector::reserve