Iterators and Ranges

Get introduced to iterators and ranges, which enable the correct use of containers and algorithms.

The standard library algorithms operate on iterators and ranges rather than container types. In this lesson, we will focus on iterators and the new concept of ranges introduced in C++20. Using containers and algorithms correctly becomes easy once we have grasped iterators and ranges.

Introducing iterators

Iterators form the basis of the standard library algorithms and ranges. Iterators are the glue between data structures and algorithms. As we have already seen, C++ containers store their elements in very different ways. Iterators provide a generic way to navigate through the elements in a sequence. By having algorithms operate on iterators rather than container types, the algorithms become more generic and flexible since they do not depend on the type of container and the way the containers arrange their elements in memory.

At its core, an iterator is an object that represents a position in a sequence. It has two main responsibilities:

  • Navigating in the sequence
  • Reading and writing the value at its current position

Get hands-on with 1200+ tech skills courses.