Search code examples
c++vectorrangestringstreamistream-iterator

Why Can't I Use istream_iterators in a vector Ctor?


I want to do this:

std::istringstream foo( "13 14 15 16 17 18 19 20" );
std::vector<int> bar( std::istream_iterator<int>( bytes ), std::istream_iterator<int>() );

But rather than recognizing it as the vector range ctor, the compiler thinks that I'm prototyping a function.

Is there a way that I can hint to the compiler what's going on?


Solution

  • If your compiler supports C++11 and uniform initialization you may do

    std::vector<int> bar{ std::istream_iterator<int>( bytes ), std::istream_iterator<int>() };
    

    If not, then change to

    std::vector bar = std::vector<int>( std::istream_iterator<int>( bytes ), std::istream_iterator<int>() );
    

    Read more about variable initialization vs function declaration ambiguity on Sutter's Mill.