如何将流cin加载到向量中

时间:2016-01-17 05:26:23

标签: c++

我想从cin加载带整数的向量。以下代码有效:

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

然而,当我尝试更简洁地写它时,它失败了:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

正如IgorTandetnik指出的那样,你遇到了C ++最烦恼的解析。解决方案(如果您的编译器理解C ++ 11)是使用统一初始化语法。

clang有一个建议,即使在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();
                 ~^~~~~

即。将您的代码更改为:

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