[英]istream_iterator and lazy evaluation
Considering istream_iterator
's lazy evaluation I was wondering if I can rely on the initialized, but never dereferenced or incremented, iterator for a condition. 考虑到
istream_iterator
的惰性评估,我想知道是否可以为条件依赖已初始化但从未取消引用或递增的迭代器。
As an example: 举个例子:
#include <iostream>
#include <fstream>
#include <iterator>
using namespace std;
int main(void)
{
ifstream file("some_directory");
istream_iterator<int> beg(file), eof;
if (beg != eof) {
//do something
}
else {
cerr << "No Input!" << endl;
}
}
Given this code sample, my question is: Is it possible that (beg != eof)
is evaluated true
even if file
is empty? 给定此代码示例,我的问题是:即使
file
为空,也可能(beg != eof)
被评估为true
吗?
Given this code sample, my question is: Is it possible that
(beg != eof)
is evaluatedtrue
even iffile
is empty?给定此代码示例,我的问题是:即使
file
为空,也可能(beg != eof)
被评估为true
吗?
No. The standard says (24.6.1/1-2) says, 否。标准说(24.6.1 / 1-2)说,
After [
istream_iterator
] is constructed, and every time++
is used, the iterator reads and stores a value ofT
.构造[
istream_iterator
]之后,每次使用++
,迭代器都会读取并存储T
的值。 If the iterator fails to read and store a value ofT
... the iterator becomes equal to the end-of-stream iterator value.如果迭代器无法读取和存储
T
...的值,则该迭代器将等于流末迭代器的值。 ... Two end-of-stream iterators are always equal....两个流结束迭代器始终相等。 An end-of-stream iterator is not equal to a non-end-of-stream iterator.
流结束迭代器不等于非流结束迭代器。 Two non-end-of-stream iterators are equal when they are constructed from the same stream.
当两个非流结束迭代器由同一流构造时,它们是相等的。
In other words, this is not as lazy as you think: 换句话说,这并不像您想的那么懒:
istream_iterator<int> beg(file)
It'll read the first int
. 它会读取第一个
int
。 If the file is empty, it fails and becomes the end-of-stream iterator right away. 如果文件为空,它将失败并立即成为流结束迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.