Consider that std::vector::push_back
is required to have amortized constant complexity (see eg here).
Reallocating all elements has linear cost.
Now imagine you would increase capacity to have space for only one additional element. This would mean that push_back
has linear complexity. The only way to get amortized constant is to reduce frequency of reallocations the more elements are in the vector.
Doubling the capacity each time the vector is full is one way to achieve that. However, implementations are free to choose different allocation strategies as long as they are in accordance with the specification and nowhere the standard says that capacity has to double.
Having said this, capacity*2+1
is probably to avoid branching for capacity== 0
each time capacity changes.
PS: Actually the article already has a teaser below that code: "We’ll see later what this does to the big-O complexity for push_back()
." and later they explore in detail how their allocation strategy ensures amortized constant complexity for push_back
.