Control over std::vector reallocation
c++, insert, stdvector, stl
Solution
You can always track it yourself and call reserve before it would allocate, e.g.
static const int N = 20 // Amount to grow by
if (vec.capacity() == vec.size()) {
vec.reserve(vec.size() + N);
}
vec.insert(...);
You can wrap this in a function of your own and call that function instead of calling `insert()` directly.
Problem
By reading the `std::vector` reference I understood that calling `insert` when the the maximum capacity is reached will cause the reallocation of the `std::vector` (causing iterator invalidation) because new memory is allocated for it with a bigger capacity. The goal is to keep the guarantee about contiguous data. As long as I stick below the maximum capacity `insert` will not cause that (and iterators will be intact). My question is the following: When `reserve` is called automatically by `insert`, is there any way to control how much new memory must be reserved? Suppose that I have a vector with an initial capacity of 100 and, when the maximum capacity is hit, I want to allocate an extra 20 bytes. Is it possible to do that?