In the code below I try to calculate the distance between two iterators. The iterators start at the same position and I advance one three times, so I feel like the distance between them 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;
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.
According to cppreference:
Two [istream] iterators are equal if both of them are end-of-stream iterators or both of them refer to the same stream.
Because your two stream iterators refer to the same stream, they are equal. It does not matter that you advanced one of them.
Since they are equal, there is 0 distance between them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With