Learn C++
#include "stlcontainers/iterators.hpp"

Iterators in C++

//concept

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.

//how it works
1

[begin, end) ranges

Every algorithm takes a half-open pair: begin() included, end() excluded — empty containers are begin()==end(), handled naturally.

2

* reads, ++ advances

*it is the current element, ++it moves on. Prefer pre-increment — postfix copies the iterator.

3

Categories set abilities

it + 5 needs random access; list and map iterators step only with ++/--. Code to the weakest category you need.

4

Respect invalidation

Vector insert may invalidate everything; erase returns a fresh valid iterator — capture it (it = v.erase(it)) and keep going.

//example
#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;
}
Output
20
10 20 30
1begin() points at 10; one ++it advances to the second element, 20.
2The const-iterator loop walks [cbegin, cend) read-only, printing each element.
3Both outputs confirm position-based access independent of indexing.
//use cases
Feeding any container to any algorithm via begin()/end() pairs
Erasing while iterating with the it = c.erase(it) idiom
Read-only passes with cbegin/cend that reject accidental writes
Reverse traversal with rbegin/rend instead of index gymnastics

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.