简体   繁体   中英

How to load stream cin into vector

I want to load a vector with integers from cin. The following code works:

std::istream_iterator< int > iterBegin( std::cin ), iterEnd;
vector< int > v( iterBegin, iterEnd );

However, when I try to write it more succinctly, it fails:

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

Any ideas?

As IgorTandetnik pointed out, you ran into C++'s Most vexing parse. The solution (if your compiler understands C++11) is to use uniform initialization syntax.

clang has a suggestion that will work even in C++98:

cin-vec.cc:7:21: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
std::vector< int > v(std::istream_iterator< int >(std::cin),
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cin-vec.cc:7:22: note: add a pair of parentheses to declare a variable
std::vector< int > v(std::istream_iterator< int >(std::cin),
                     ^
                     (                                     )
cin-vec.cc:12:19: error: member reference base type 'std::vector<int> (std::istream_iterator<int>, std::istream_iterator<int> (*)())' is not a structure or union
    std::cout << v.size();
                 ~^~~~~

ie change your code to:

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

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