Cannot access vector when constructing with istream_iterator range

主宰稳场 提交于 2020-01-13 20:28:11

问题



I tried to compile this code snippet but I got compiler error :( ! Compile with Visual Studio 2010

#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <iostream>

using namespace std;

int main() {
    string s( "Well well on" );
    istringstream in( s );
    vector<string> v( istream_iterator<string>( in ), istream_iterator<string>() );
    copy( v.begin(), v.end(), ostream_iterator<string>( cout, "\n" ) );
}

Errors:

Error   1   error C2228: left of '.begin' must have class/struct/union  c:\visual studio 2008 projects\vector test\vector test\main.cpp 13  vector test
Error   2   error C2228: left of '.end' must have class/struct/union    c:\visual studio 2008 projects\vector test\vector test\main.cpp 13  vector test

What happened? vector was constructed correctly, how could I not be able to call it?

Best regards,


回答1:


I think this

vector<string> v( istream_iterator<string>( in ), istream_iterator<string>() );

is parsed as a function declaration:

vector<string> v( istream_iterator<string> in, istream_iterator<string> );

This is usually called "C++' most-vexing parse".

I think a few extra parentheses will cure this:

vector<string> v( (istream_iterator<string>(in)), (istream_iterator<string>()) );



回答2:


This is an example of the so-called most vexing parse. It;'s a gotcha that stings many C++ programmers.

Basically, this code doesn't mean what you think it means:

vector<string> v( istream_iterator<string>( in ), istream_iterator<string>() );

Instead of declaring a variable of type vector<string>, you are actually declaring a function named v that returns vector<string>.

To fix this, use operator= like this:

vector<string> v = vector<string>( istream_iterator<string>( in ), istream_iterator<string>() );



回答3:


The parser thinks the following line is declaring a function:

vector<string> v( istream_iterator<string>( in ), istream_iterator<string>() );

Change your main to this and it will compile:

int main() 
{
    string s( "Well well on" );
    istringstream in( s );
    istream_iterator<string> start = istream_iterator<string>(in);
    vector<string> v(start, istream_iterator<string>());
    copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n"));
}


来源:https://stackoverflow.com/questions/4511733/cannot-access-vector-when-constructing-with-istream-iterator-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!