STL Algorithms and Iterators
Write less loop code, express more intent
<algorithm> do the work. Iterators are the glue: because std::sort talks only to iterators, the very same algorithm runs over a vector, an array, or a raw C array.
- explain the container / iterator / algorithm separation,
- use the half-open range
[begin, end)correctly, - name the five iterator categories and what each one allows,
- call
sort,find,count_if,transformandaccumulatewith lambdas, - recognise where C++20
rangesmake the same code shorter and safer.
1. Three parts that fit together
Before the STL you would write a raw loop for every task: one loop to sort, another to search, another to add up. The STL factors that into reusable pieces. An algorithm such as std::sort knows how to sort but nothing about where the data lives. An iterator is a small object that behaves like a pointer: you dereference it with *it to read the element and advance it with ++it. A container such as std::vector hands you iterators through begin() and end().
The payoff is reuse: write an algorithm once, and it works on any container that exposes the right kind of iterator. This is why the STL feels small yet does so much.