Skip to content

Iterators & Ranges

Iterators abstract positions in a sequence (begin, end). Ranges (C++20) pair iterator + sentinel; classic CP code still uses two-iterator APIs everywhere.

Basics

#include <vector>
#include <algorithm>
using namespace std;

void example(vector<int>& a) {
    sort(a.begin(), a.end());
    auto it = lower_bound(a.begin(), a.end(), 42);
    if (it != a.end() && *it == 42) { /* found */ }
}
  • [begin, end) is half-open: end is one past the last element.
  • Reverse iterators: rbegin, rend for backward traversal.

Invalidation

  • vector / string: inserting or erasing can invalidate iterators at or after the change (reallocation invalidates all).
  • map / set: only iterators to erased elements are invalidated.

Erase–remove idiom

a.erase(remove(a.begin(), a.end(), value), a.end());