How do I avoid reallocation and iterator invalidation with std::vector?

When using std::vector in C++, it's crucial to understand how reallocations can affect the stability of your iterators. Reallocation occurs when the vector exceeds its current capacity, leading to invalidation of iterators, pointers, and references to its elements. To avoid reallocation and ensure iterator stability, you can reserve enough space in advance and manipulate the vector carefully.

Here’s how you can prevent reallocation:

  • Use reserve() to allocate enough memory for expected elements.
  • Use emplace_back() or push_back() only after reserving enough capacity.
  • Avoid frequent resizing or inserting large amounts of elements without reservation.

Below is an example demonstrating how to use std::vector with capacity reservation to avoid iterator invalidation:

#include <iostream>
#include <vector>

int main() {
    std::vector vec;
    vec.reserve(10); // Reserve capacity for 10 elements

    for (int i = 0; i < 10; ++i) {
        vec.push_back(i);
    }

    // Using an iterator safely after reserving capacity
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    return 0;
}

std::vector C++ iterator invalidation reallocation memory management