如何正确使用向量范围构造函数? [英] How to properly use a vector range constructor?

查看:146
本文介绍了如何正确使用向量范围构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用范围构造函数将文本文件中的所有行加载到向量< string 中,然后通过 cout

I want to load all the lines from a text file into a vector<string by using its range constructor and then output them through cout:

#include<iostream>
#include<fstream>
#include<vector>
#include<iterator>

using namespace std;

int main()
{
  ifstream file("file.txt");
  vector<string> strings(istream_iterator<string>(file) , istream_iterator<string>());

  for(auto s : strings)
    cout << s << endl;

  return 0;
}



当尝试编译上面的代码时,我得到几个错误,例如: / p>

When trying to compile the above code I get several errors, for instance:

error: no matching function for call to ‘begin(std::vector<std::basic_string<char> > (&)    (std::istream_iterator<std::basic_string<char> >, std::istream_iterator<std::basic_string<char> > (*)    ()))’
   for(auto s : strings)
                ^

和其他几个...

我想我缺少这里明显的东西,任何人都可以帮忙吗?

I think I'm missing something obvious here, can anyone please help?

推荐答案

到最多Vexing解析,其中编译器将您的声明视为 strings 返回向量< string> 两个参数:

You have fallen victim to the Most Vexing Parse, where the compiler sees your declaration as a function strings returning a vector<string>, taking two arguments:


  • istream_iterator< string> 文件

  • 一个未命名的函数指针,不带参数并返回 istream_iterator< string> li>
  • an istream_iterator<string> called file
  • an unnamed pointer to function taking no arguments and returning a istream_iterator<string>.

要消除烦人的解析,请在第一个参数周围使用一对额外的括号:

To eliminate the vexing parse, use an extra pair of parentheses around the first argument:

vector<string> strings((istream_iterator<string>(file)) , istream_iterator<string>());
//                     ^                              ^

或者,在C ++ 11中,使用大括号 strings 构造函数

or, alternatively in C++11, use curly braces for the strings constructor

vector<string> strings{istream_iterator<string>(file) , istream_iterator<string>()};
//                    ^                                                           ^

注意:Clang警告您它通过 -Wvexing-parse (默认情况下已启用)。

NOTE: Clang warns you about it through -Wvexing-parse (on by default).

这篇关于如何正确使用向量范围构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆