Iterators in C++
Iterators are the STL's universal pointers: begin() points at the first element, end() one past the last (never dereference it!), and ++ advances. Algorithms are written against iterator pairs, which is why the same std::sort and std::find work on vectors, deques, lists, and raw arrays alike.
Categories matter: random-access (vector) supports jumps and arithmetic, bidirectional (list, map) steps both ways, forward-only steps ahead. Const iterators (cbegin) forbid writes; reverse iterators (rbegin) walk backward. Invalidation rules differ per container — vector reallocates, list never does.
[begin, end) ranges
Every algorithm takes a half-open pair: begin() included, end() excluded — empty containers are begin()==end(), handled naturally.
* reads, ++ advances
*it is the current element, ++it moves on. Prefer pre-increment — postfix copies the iterator.
Categories set abilities
it + 5 needs random access; list and map iterators step only with ++/--. Code to the weakest category you need.
Respect invalidation
Vector insert may invalidate everything; erase returns a fresh valid iterator — capture it (it = v.erase(it)) and keep going.
#include <iostream>#include <vector> int main() { std::vector<int> v{10, 20, 30}; auto it = v.begin(); ++it; std::cout << *it << std::endl; for (auto i = v.cbegin(); i != v.cend(); ++i) { std::cout << *i << " "; } std::cout << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.