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:endis one past the last element.- Reverse iterators:
rbegin,rendfor 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¶
Related¶
- Sets and Maps — iterator-based lookup
- Two Pointer / Sliding Window — index pairs as positions