In the code below I try to calculate the distance between two iterators. The iterators start at the same position and I advance once three times, so I feel like the distance between the two should be three, but I always get 0. Why?
using namespace std;
stringstream strstream{"Hello world"};
auto b = istream_iterator<char>{strstream};
auto e = istream_iterator<char>{strstream};
++e;
++e;
++e;
cout << "distance: " << distance(b,e) << endl;
>Solution :
This is because input iterators only guarantee a single pass. The following is from cppreference about the operator++ of an input iterator:
++r[…]
Postcondition: Any copies of the previous value of r are no longer required to be either dereferenceable or to be in the domain of ==.
So, after ++e, b no longer has any guarantee on its value or if it is even usable.