The weird result of istream_iterator in C++

250 views Asked by At
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <list>
using namespace std;

int main()
{
    istream_iterator<int> in_iter(cin);
    istream_iterator<int> eof;
    vector<int> vin;
    /*while (in_iter!=eof)
    {
        vin.push_back(*in_iter++);
    }*/
    istream_iterator<int> in_iter2(cin), eof2;
    vector<int> vin2(in_iter2,eof2);
    return 0;
}

When I input 1 2 3 c (the last element 'c' is to make the cin state to EOF)to the program,finally,vin2 will contain elements: 2 3;However,when I annotate the declaration of variable in_iter,the same input will make vin2 contain elements:1 2 3;How does the declaration of variable in_iter make effect to this program?Thanks!

1

There are 1 answers

0
Benjamin Lindley On BEST ANSWER

The binding of an istream_iterator to an istream causes one value to be read from the istream, and stored in the iterator. This is necessary so that dereferening the iterator can give a value. So if you bind 2 istream_iterators to the same istream, 2 values will be read.

It's rarely useful to have 2 active istream iterators bound to the same istream.

As an mildly interesting experiment, see what happens if you create both in_iter and in_iter2, both bound to cin, and initialize your vector with in_iter (or whichever one was created first).