简体   繁体   中英

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

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> v(istream_iterator<int>(cin), istream_iterator<int>()); //Compilation error?!
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));

    return 0;
}

Why that line goes error? I know the compiler thouht 'v' as a function! Amazing...

This problem is known as C++'s most vexing parse .

Try changing the first line to the following (note the extra parentheses):

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

As specified by @Kyle Lutz, it's the most vexing parse problem, that is also often solved by changing the initialization to something like:

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

which tends to be better understood than the "double parenthesis trick".

Here there are function pointer declarations used as a function parameter:

int f(int (*funa)());
int f(int funa());
int f(int());//The parameter name can be omitted, such as the function declaration int g(double p); is equal to int g(double);

So, look at your problem:

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

Yes, yes, we know istream_iterator<int>(cin) is a istream_iterator<int> type parameter. However, the second parameter is the problem we encounter: istream_iterator<int>() can be understood as a pointer to a function which returns istream_iterator<int> and has no parameters. This makes compiler confused, v may be a function declaration or a verb definition. If the second parameter is not a function pointer, v is a verb definition.

We can fix your problem by two ways, first you can declare the iterators and then use them in v :

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

The second way to fix it is :

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

we add () around the first element which tells the compiler it is a verb, not a parameter, so the second element must be a verb too. That's all.

当我尝试编译它时,我遇到的唯一错误是在下一行,它抱怨v.begin()v.end()无效,因为v不是类/结构/联合(对于正如已经指出的那样,很明显的原因是您遇到了最烦人的解析)。

If you would just add one extra line, your could avoid the MVP, and your code would, imo, be much more readable, and less repetetive.

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

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