Nov 15, 2007

initializing vector with ostream_iterator

To someone it could be useful :)
When you try to compile the following code:


vector<int> v( istream_iterator<int>(cin), istream_iterator<int>() );


you actually end up with several error messages. Here g++ compile (for example), will follow the standard, and will identify the definition of v as a forward declaration of a function accepting two istream_iterator parameters and returning a vector of integers.

  • #1. Solution which works for g++ 4.1< (the extra set of parenthesis for the last argument of vector's ctor)
     vector<int> v( istream_iterator<int>(cin), (istream_iterator<int>()) );


but this doesn't really works with g++3.2

  • #2. Solution for g++ 3.2> - actually a general solution, which should work always:

typedef istream_iterator<int> in_iter;
in_iter b(cin);
in_iter e;
vector<int> v( b, e );

No comments: