C++ std::vector::reserve
Reserve capacity before appending readings to a vector that already contains a value.
A simple example
std::vector::reserve
- Start with An empty vector
- Do this Reserve room for three items
- Result Size 0, capacity at least 3
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
./lessonMake 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.
#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;
}
12, 15
The original twelve survives the capacity change. Appending fifteen then increases the size to two.
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?
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?
What to watch for
reserve changes capacity, not size. Reallocation can invalidate pointers and iterators.