简体   繁体   English

使用istream_iterator范围进行构造时无法访问向量

[英]Cannot access vector when constructing with istream_iterator range


I tried to compile this code snippet but I got compiler error :( ! Compile with Visual Studio 2010 我尝试编译此代码段,但出现编译器错误:(!使用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, 最好的祝福,

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" . 通常将其称为“ C ++最令人烦恼的解析”

I think a few extra parentheses will cure this: 我认为可以在括号中加上一些括号来解决此问题:

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

This is an example of the so-called most vexing parse . 这是所谓的最烦人的解析的一个例子。 It;'sa gotcha that stings many C++ programmers. 这是一个困扰许多C ++程序员的陷阱。

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> . 您实际上不是在声明一个类型为vector<string>的变量,而是在声明一个名为v函数 ,该函数返回vector<string>

To fix this, use operator= like this: 要解决此问题,请像这样使用operator=

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

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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM