In this section, we will implement a primitive iterator that counts numbers and use it together with an STL algorithm, which initially does not compile with it. Then we do what's necessary to make it STL-compatible.
- First, we need to include some headers, as always:
#include <iostream>
#include <algorithm>
- Then we implement a primitive number counting iterator, as in the previous section. When iterating over it, it will emit plain increasing integers. The num_range acts as a handy begin and end iterator donor:
class num_iterator
{
int i;
public:
explicit num_iterator(int position = 0) : i{position} {}
int operator*() const { return i; }
num_iterator& operator++() {
++i;
return *this;
}
bool operator!=(const num_iterator &other) const {
return i != other.i;
}
bool operator==(const num_iterator &other) const {
return !(*this != other);
}
};
class num_range {
int a;
int b;
public:
num_range(int from, int to)
: a{from}, b{to}
{}
num_iterator begin() const { return num_iterator{a}; }
num_iterator end() const { return num_iterator{b}; }
};
- In order to keep the std:: namespace prefix out and keep the code readable, we declare that we use namespace std:
using namespace std;
- Let's now just instantiate a range that goes from 100 to 109. Note that the value 110 is the position of the end iterator. This means that 110 is the first number that is outside the range (which is why it goes from 100 to 109):
int main()
{
num_range r {100, 110};
- And now, we use it with std::minmax_element. This algorithm returns us std::pair with two members: an iterator pointing to the lowest value and another iterator pointing to the highest value in the range. These are, of course, 100 and 109 because that's how we constructed the range:
auto [min_it, max_it] (minmax_element(begin(r), end(r)));
cout << *min_it << " - " << *max_it << 'n';
}
- Compiling the code leads to the following error message. It's some error related to std::iterator_traits. More on that later. It might happen that there are other errors on other compilers and/or STL library implementations or no errors at all. This error message occurs with clang version 5.0.0 (trunk 299766):

- In order to fix this, we need to activate iterator trait functionality for our iterator class. Just after the definition of num_iterator, we write the following template structure specialization of the std::iterator_traits type. It tells the STL that our num_iterator is of the category forward iterator, and it iterates over int values:
namespace std {
struct iterator_traits<num_iterator> {
using iterator_category = std::forward_iterator_tag;
using value_type = int;
using difference_type = void;
using pointer = int*;
using reference = int&;
};
}
- Let's compile it again; we can see that it works! The output of the min/max function is the following, which is just what we expect:
100 - 109