gpt4 book ai didi

c++ - 为什么多输入迭代器会导致意想不到的结果?

转载 作者:行者123 更新时间:2023-11-30 02:53:46 26 4
gpt4 key购买 nike

下面是示例代码和在linux下使用gcc4.8.1编译的结果:

//content of test.txt
1 2 3 4 5

int main()
{
fstream fs ("test.txt", std::fstream::in );
istream_iterator<string> is1(fs),eof1;
istream_iterator<string> is2(fs),eof2;

while(is1!=eof1){
cout<<"is1:"<<*is1++<<endl;
}
while(is2!=eof2){
cout<<"is2:"<<*is2++<<endl;
}


return 0;
}


//result unexpected
$./m
is1:1
is1:3
is1:4
is1:5
is2:2

从结果中我们可以看出,当使用多输入迭代器时,它会给出意想不到的结果。有人可以提示我为什么会发生这种情况吗?

最佳答案

这在 24.6.1/1 中得到了回答:

The class template istream_iterator is an input iterator (24.2.3) that reads (using operator>>) successive elements from the input stream for which it was constructed. After it is constructed, and every time ++ is used, the iterator reads and stores a value of T.

因此,当您创建 is1 时,它会读取 1。当您创建 is2 时,它会读取 2,然后您使用 is1 遍历文件的其余部分。最后,您打印从 is2 中提取的单个值,然后结束其迭代。

关于c++ - 为什么多输入迭代器会导致意想不到的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com