开发者

distance makes my iterator "freeze"

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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜