Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does std::distance return zero?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading