Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distance makes my iterator "freeze"

Tags:

c++

iterator

Try this:

int main()
{
    std::fstream fin_fout("some.txt");
    std::istream_iterator<std::string> beg(fin_fout),end;
    std::distance(beg,end);//if this line is commented out it works fine but not if is uncommented
    while (beg != end)
    {
      cout << *beg;
      ++beg;
    }
    return 0;
}
like image 699
smallB Avatar asked Dec 06 '22 21:12

smallB


1 Answers

distance on an input iterator will repeatedly call operator++. However, this operation invalidates all copies of the iterator, because they all refer to the same underlying stream

This is logical: consider what the iterator represents: the current state of the input stream. As soon as you advance the iterator, that state changes. All other iterators representing the old state are therefore now referring to a state that no longer exists.

This is why you see this behaviour.

Getting a distance from two stream operators is moreover not a meaningful operation since streams don’t have a fixed length: streams represent transient state.

like image 142
Konrad Rudolph Avatar answered Dec 22 '22 21:12

Konrad Rudolph