Skip to content

STL Algorithms and Iterators

Beginning of the lesson

STL Algorithms and Iterators

Write less loop code, express more intent

Big Idea: The Standard Template Library (STL) splits data work into three cooperating parts: containers hold the data, iterators point into it, and algorithms in <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.
By the end you will be able to:
  • 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, transform and accumulate with lambdas,
  • recognise where C++20 ranges make 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.

Container vector, array, list... begin() end() Iterators *it ++it Algorithm sort, find... exposes drives One algorithm, many containers - iterators are the shared contract.
Containers expose iterators; algorithms operate through those iterators.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers