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.
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?
Given this code sample, my question is: Is it possible that
(beg != eof)
is evaluatedtrue
even iffile
is empty?
No. The standard says (24.6.1/1-2) says,
After [
istream_iterator
] is constructed, and every time++
is used, the iterator reads and stores a value ofT
. If the iterator fails to read and store a value ofT
... the iterator becomes equal to the end-of-stream iterator value. ... 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
. If the file is empty, it fails and becomes the end-of-stream iterator right away.