Iterators & Algorithms
The Universal Remote
Imagine you have a TV, a Blu-ray player, and a sound system β each from a different brand. Instead of learning three different remotes, you get a universal remote that works with all of them.
That's what iterators are in C++. Whether your data lives in a vector, a map, a set, or a list, iterators give you one consistent interface to walk through elements. And algorithms are the pre-programmed buttons on that remote β sort, search, transform, count β all ready to go.
begin() and end()
Every STL container provides two key iterators:
begin()β points to the first elementend()β points one past the last element (a sentinel, not a real element)
This half-open range [begin, end) is the foundation of every algorithm. It means: "start here, stop before here."
Iterator Categories
Not all iterators are equal. They form a hierarchy:
- Input β Read forward once (e.g., reading from a stream)
- Output β Write forward once
- Forward β Read/write, multiple passes (e.g.,
forward_list) - Bidirectional β Forward + backward (e.g.,
list,map,set) - Random Access β Jump anywhere in O(1) (e.g.,
vector,deque)
Algorithms require a minimum iterator category. std::sort needs random access, so it works on vectors but not lists.
Sorting a Vector
find and count
transform β Convert to Uppercase
accumulate β Sum and Custom Fold
The Remove-Erase Idiom
This is one of the most important C++ patterns. std::remove does NOT actually remove elements from a container. It moves the elements you want to keep to the front and returns an iterator to the new "logical end." The container's size doesn't change! You must call erase() to actually shrink it.
Remove-Erase Idiom
C++20 Ranges (Preview)
C++20 introduced ranges β a cleaner way to use algorithms. Instead of passing begin() and end() separately, you pass the container directly:
// Old way
std::sort(v.begin(), v.end());
// C++20 ranges
std::ranges::sort(v);Ranges also support views β lazy, composable transformations that don't copy data. This is the future of C++ algorithms.