CKTIS / C++
Iterator invalidation in C++: the std::vector case
Learn when a vector mutation invalidates iterators, references, and pointers, including the past-the-end iterator, and how to use a std::find_if result safely.
Version: ISO C++23; implementation support may vary
Syntax
// ISO C++23; implementation support may vary
// For v of type const std::vector<int>& and a unary predicate pred:
auto it = std::find_if(v.begin(), v.end(), pred);
const int* result = (it == v.end()) ? nullptr : &*it;Iterator invalidation (iterator invalidation) means an iterator can no longer be used to traverse its range or access an element. The rules depend on the container and operation. Do not dereference, advance, or compare an invalidated iterator, even against a freshly obtained end().
std::vector::begin() identifies the first element, and std::vector::end() marks the position past the last element. They compare equal for an empty vector. The const overloads return const_iterator; the non-const overloads return iterator. std::find_if from <algorithm> searches the half-open range [v.begin(), v.end()) and returns an iterator to the first matching element, or the supplied end() if there is no match. Check the result before dereferencing. For const std::vector<int>&, &*it gives a non-owning const int*; return nullptr on a miss. Do not apply this address-taking pattern to std::vector<bool>. Because first_even takes a const reference, it accepts a temporary vector. If you pass one directly, any non-null pointer it returns dangles at the end of the full-expression containing the call.
Reallocation invalidates all element iterators, references, and pointers, plus the old end(). A successful reserve(n) reallocates exactly when n > capacity(), without changing size(). Insertion without reallocation preserves handles strictly before the insertion point but invalidates those at or after it, including the old end(). Thus push_back without reallocation preserves handles to existing elements, but not the old end().
erase invalidates iterators and references at or after the erasure point, including the old end(); do not use a pointer to an erased element to access the original match. To continue iterating, use the iterator returned by erase, which denotes the next element or the new end(). clear() destroys every element, invalidating all iterators, references, and pointers to elements. Obtain a fresh end() afterward. A const int* neither extends the element's lifetime nor protects it from vector mutations. After an invalidating operation, search again, or copy the value beforehand if that is all you need.
Examples
#include <algorithm>
#include <iostream>
#include <vector>
const int* first_even(const std::vector<int>& v) {
const auto it = std::find_if(v.begin(), v.end(),
[](int x) { return x % 2 == 0; });
return it == v.end() ? nullptr : &*it;
}
int main() {
std::vector<int> v{1, 4, 7};
v.reserve(4);
{
const int* p = first_even(v);
if (!p) return 1;
std::cout << *p << '\n';
v.push_back(6);
std::cout << *p << '\n';
}
v.erase(v.begin() + 1);
if (const int* p = first_even(v)) {
std::cout << *p << '\n';
}
v.clear();
if (!first_even(v)) {
std::cout << "no match\n";
}
}Result
4 4 6 no match
`reserve(4)` leaves room to append `6`: the pointer to `4` stays valid, but the old `end()` does not. After `4` is erased, a fresh search finds `6`; after `clear()`, there is no match.
Related lessons
- C++ · Lesson 10 · Advanced · Version: 3
Sources
- N4950 — Working Draft, Standard for Programming Language C++
- Container requirements [container.reqmts]
- Find [alg.find]
- Iterator requirements, general [iterator.requirements.general]
- Vector capacity [vector.capacity]
- Vector modifiers [vector.modifiers]
- Sequence container requirements [sequence.reqmts]
- Partial class template specialization vector<bool, Allocator> [vector.bool.pspc]