I often used istream_iterator copy standard input to a vector like this:
copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(vec));
it works.
Today when i construct a vector by this:
vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
it just can not compile!
But if i construct it like this:
istream_iterator<int> beg(cin), end;
vector<int> vec(beg, end);
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
it works.
Why? Can not i use temporary variables to construct a vector? If it does, but why could i do it when i use std::copy?
ps: I compiled it under vs2005 and i used the following head files:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
Unfortunately, this is a function declaration:
It's a function named
vec
, that returns avector<int>
by value and takes two parameters: anistream_iterator<int>
with a formal parameter name ofcin
, and a function with no formal parameter name that returns anistream_iterator<int>
, and takes no parameters.Why?
Basically, in C++(and C), if a piece of code can be interpreted as a declaration, it will be.
According to N3936::6.8.1 [stmt.ambig]:
How to fix it
All we need is something that makes it impossible for the compiler to treat the code as a function declaration.
Adding the extra parentheses around the parameters makes it clear to the compiler that what we intend to be constructor parameter names can't be parameter declarations.
vector<int> vec((istream_iterator<int>(cin)), istream_iterator<int>());
As your solution showed, using named variables as constructor parameters.