How does std::vector manage its internal memory when it reaches capacity, and what is the amortized time complexity of an insertion?
Last updated
When
size() == capacity(), the vector allocates a larger buffer (typically 1.5x or 2x), transfers elements, and frees the old one, invalidating all iterators, pointers, and references.Geometric growth means n insertions cost O(n) total work, so
push_backis amortized O(1) even though individual reallocations are O(n).Elements are moved if the move constructor is
noexcept, otherwise copied. Callreserve()up front to avoid reallocations.