Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::distance return zero?

Tags:

c++

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;
like image 592
dB' Avatar asked Aug 26 '26 20:08

dB'


2 Answers

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.

like image 102
NathanOliver Avatar answered Aug 28 '26 11:08

NathanOliver


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.

like image 33
Drew Dormann Avatar answered Aug 28 '26 10:08

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!