简体   繁体   中英

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.

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 evaluated true even if file 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 of T . If the iterator fails to read and store a value of T ... 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM