vector growth and iterator invalidation

Difficulty: Intermediate

Question

How does std::vector grow? What is the difference between size and capacity, and which operations invalidate iterators?

Answer

std::vector is the container you will use ninety percent of the time, and interviewers like it because a proper explanation touches memory, complexity and correctness all at once. Let's go through how it grows and what can go wrong.

A vector stores its elements in a contiguous block of heap memory and tracks three things: a pointer to the start, the size (number of elements in use), and the capacity (how many it can hold before needing more space). When you push_back into a full vector, it allocates a larger block, typically 1.5x (MSVC) or 2x (GCC and Clang) the old capacity, moves or copies every element to the new block, and frees the old one. The exact factor is implementation-defined. Think of a bookshelf: when it is full, you buy a bigger one and carry every book across. If you always buy one that is twice the size, the trips become rare.

That is why push_back is amortised O(1). Any individual push_back that triggers reallocation costs O(n), but since capacity grows geometrically, the total cost of n insertions is O(n), so the average per insertion is constant. If you know the final size, call reserve(n) up front to avoid all intermediate reallocations. Note the difference between reserve (changes capacity only, size unchanged) and resize (changes the number of elements, default-constructing new ones). Also, shrink_to_fit is a non-binding request to release excess capacity, and clear() destroys elements but usually keeps the capacity.

Now the danger: iterator, pointer, and reference invalidation. If an insertion causes reallocation, all iterators, pointers and references to elements are invalidated because the elements now live at new addresses. If no reallocation occurs, only iterators at or after the insertion point are invalidated. Erasing an element invalidates iterators and references at and after the erased position. A loop that does 'for (auto it = v.begin(); it != v.end(); ++it) if (cond) v.erase(it);' is therefore a bug. The correct pattern is 'it = v.erase(it)' when erasing, else '++it', since erase returns the iterator to the next element.

For removing many elements, use the erase-remove idiom: 'v.erase(std::remove_if(v.begin(), v.end(), pred), v.end());'. std::remove_if shifts the elements to keep to the front and returns the new logical end; erase then truncates the tail. In C++20, std::erase_if(v, pred) does it in one call.

Other well-known items: push_back(x) with x referencing an element of the same vector is handled correctly by the standard library, and emplace_back constructs the element in place, avoiding a temporary. Vectors of bool are a special packed specialization and behave differently. In a competitive or interview setting, inserting or erasing in the middle is O(n) due to shifting, so prefer a deque, list, or a different algorithm if that is your dominant operation.

Code examples

Erase safely and reserve ahead

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    v.reserve(100);                       // capacity >= 100, size still 0
    for (int i = 1; i <= 10; ++i) v.push_back(i);
    std::cout << v.size() << " " << (v.capacity() >= 100) << "\n";

    // Erase-remove idiom: drop even numbers
    v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";

    // Correct manual erase loop: use the iterator returned by erase
    for (auto it = v.begin(); it != v.end();) {
        if (*it > 5) it = v.erase(it);
        else ++it;
    }
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";
}

reserve prevents reallocation during the pushes. remove_if plus erase removes the evens; the manual loop shows the safe way to erase while iterating.

Key points

Common follow-up questions

Interview tips

Concepts covered

std::vector, capacity, iterator invalidation, amortized complexity, erase-remove

More C++ & STL questions