Legacy C++ › 6. The Standard Template Library
Iterators
Iterator categories, invalidation rules and iterator adaptors.
Explanation
An iterator is a pointer-like object that points into a container. The STL’s design: containers expose iterators, algorithms consume iterator ranges, so any algorithm works with any container.
A range is half-open: [begin, end), where end() is one past the last element and must not be dereferenced.
Iterator categories (each adds abilities to the previous):
| Category | Abilities | Examples |
|---|---|---|
| Input / Output | single pass read / write | istream_iterator, ostream_iterator |
| Forward | multi-pass, ++ |
slist, (C++11 forward_list) |
| Bidirectional | adds -- |
list, set, map |
| Random access | adds + n, -, <, [] |
vector, deque, arrays |
Variants: iterator, const_iterator (cannot modify), reverse_iterator (rbegin()/rend()). Adaptors: std::back_inserter(c), front_inserter, inserter turn assignment into insertion.
Example
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
int main() {
std::vector<int> v;
for (int i = 1; i <= 5; ++i) v.push_back(i);
for (std::vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
std::cout << *it << " ";
std::cout << "\n";
for (std::vector<int>::reverse_iterator r = v.rbegin(); r != v.rend(); ++r)
std::cout << *r << " "; // 5 4 3 2 1
std::cout << "\n";
std::vector<int>::iterator it = v.begin() + 2; // random access: + n
std::cout << *it << " dist=" << std::distance(v.begin(), it) << "\n";
std::list<int> out;
std::copy(v.begin(), v.end(), std::back_inserter(out)); // grows the list
std::copy(out.begin(), out.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << "\n";
std::list<int>::iterator li = out.begin();
std::advance(li, 3); // works for any category
std::cout << *li << "\n";
return 0;
}
Common pitfalls
- Invalidation:
vector::insert/push_backmay invalidate all iterators;eraseinvalidates those at/after the position;listandmaponly invalidate the erased element. - Dereferencing
end()or incrementing past it is undefined behavior. - Comparing iterators from different containers is undefined.
it < endworks only for random-access iterators; use!=everywhere.- Writing through
copyinto an empty container without an inserter overwrites nothing and corrupts memory.
Legacy vs modern
C++11 adds auto it = v.begin();, std::begin/end, std::next/prev and range-based for. C++20 ranges and views replace explicit iterator pairs. See Ranges and Views.
Exercises
1. Why prefer ++it over it++ for iterators?
Postfix returns a copy of the old iterator, which can be needlessly costly for non-pointer iterators. Prefix returns a reference with no copy.