Search⌘ K
AI Features

Iterators and Ranges

Explore the concepts of iterators and ranges introduced in C++20, essential for navigating data structures and enabling flexible, generic algorithms. Understand how iterators act as pointers within sequences and the role of sentinel values and past-the-end iterators. Learn how ranges simplify iterator-sentinel pairs and how modern algorithms operate on these abstractions to enhance code performance and readability.

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
Iterator in C++
Iterator in C++

The iterator abstraction is not at all a C++ exclusive concept, rather, it exists in most programming languages. What ...