Search⌘ K
AI Features

Make Our Iterators Compatible with STL Iterator Traits

Understand how to modify custom C++ iterators to conform with STL iterator traits, enabling their use with standard algorithms like minmax_element. Explore adding necessary operators and type aliases to meet forward iterator specifications across compilers, improving iterator compatibility.

We'll cover the following...

Many STL algorithms require iterators to conform to certain traits. Unfortunately, these requirements are inconsistent across compilers, systems, and C++ versions.

For our purposes, we'll use the class from the Create an Iterable Range recipe to illustrate the issue. You may find this makes more sense if you read that recipe before continuing.

In main(), if we add a call to the minmax_element() algorithm:

Seq<int> r{ 100, 110 };
auto [min_it, max_it] = minmax_element(r.begin(), r.end());
cout << format("{} - {}\n", *min_it, *max_it);

It does not compile. The error messages are vague, cryptic, and cascading, but if we look closely, we'll see that our iterator does not meet the requirements to be compatible with this algorithm. ...