C++ · Module 13 · Lesson 71 min read

Iterators & Iterator Invalidation

Iterator basics

scss
auto it = v.begin();   // points to the first element
*it                    // the element
it->member             // member of the element
++it / --it            // next / previous
it + 3, it - v.begin() // random-access iterators only

cbegin()/cend() give const iterators (read-only). rbegin()/rend() go backwards.

Helper functions (<iterator>)

std::next(it, n), std::prev(it, n), std::advance(it, n), std::distance(a, b) — work for any iterator category.

Iterator invalidation ⚠️

An iterator (or pointer/reference) is invalidated when the element it refers to moves or disappears. Using it is undefined behaviour.

ContainerInsert invalidatesErase invalidates
vector / stringall if it reallocates; otherwise those at/after the pointat/after the erased element
dequeall iterators (references stay valid when inserting at the ends)depends; ends mostly safe
list, forward_listnothingonly the erased element
map, setnothingonly the erased element
unordered_*all iterators if it rehashesonly the erased element

Erasing while iterating — the correct pattern ✅

erase returns the iterator to the next element:

ini
for (auto it = v.begin(); it != v.end(); ) {
    if (should_remove(*it)) it = v.erase(it);
    else ++it;
}

Even simpler: std::erase_if(container, pred) (C++20) — works for vector, list, map, set, unordered containers.

Inserting while iterating

Avoid it. Collect changes in a separate container and apply them after the loop.

Special iterators

  • std::back_inserter(v) — writing to it calls push_back
  • std::istream_iterator<int> / std::ostream_iterator<int> — read/write streams like ranges
  • Reverse iterators: it.base() converts back

Example

C++
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <sstream>
#include <vector>

int main() {
    std::vector<int> v = { 10, 25, 30, 45, 50, 65 };

    auto it = v.begin();
    std::advance(it, 2);
    std::cout << "*it = " << *it << ", next = " << *std::next(it) << ", prev = " << *std::prev(it)
              << ", distance from begin = " << std::distance(v.begin(), it) << '\n';

    // erase odd numbers with the correct pattern
    for (auto i = v.begin(); i != v.end();) {
        if (*i % 2 != 0) i = v.erase(i);     // erase returns the next valid iterator
        else ++i;
    }
    std::cout << "evens:";
    for (int x : v) std::cout << ' ' << x;
    std::cout << '\n';

    // C++20: one line
    std::map<std::string, int> stock = { { "pen", 0 }, { "notebook", 12 }, { "eraser", 0 }, { "ruler", 3 } };
    auto removed = std::erase_if(stock, [](const auto& kv) { return kv.second == 0; });
    std::cout << "removed " << removed << " out-of-stock items, left:";
    for (const auto& [item, qty] : stock) std::cout << ' ' << item << '(' << qty << ')';
    std::cout << '\n';

    // list iterators survive insertions elsewhere
    std::list<int> l = { 1, 2, 3 };
    auto keep = std::next(l.begin());       // points to 2
    l.push_front(0);
    l.push_back(4);
    std::cout << "list iterator still valid: " << *keep << '\n';

    // vector: a reallocation invalidates references, so take the index instead
    std::vector<int> data = { 7 };
    data.shrink_to_fit();
    std::size_t index_of_first = 0;          // indexes survive reallocation; iterators may not
    for (int i = 0; i < 100; ++i) data.push_back(i);
    std::cout << "first element via index: " << data[index_of_first] << '\n';

    // stream iterators and back_inserter
    std::istringstream in("5 15 25");
    std::vector<int> from_stream(std::istream_iterator<int>{ in }, std::istream_iterator<int>{});
    std::copy(from_stream.begin(), from_stream.end(), std::back_inserter(v));
    std::cout << "v after back_inserter: ";
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\nbackwards: ";
    std::copy(v.crbegin(), v.crend(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
    return 0;
}

/* Output:
*it = 30, next = 45, prev = 25, distance from begin = 2
evens: 10 30 50
removed 2 out-of-stock items, left: notebook(12) ruler(3)
list iterator still valid: 2
first element via index: 7
v after back_inserter: 10 30 50 5 15 25
backwards: 25 15 5 50 30 10
*/