如何使用向量和对象构造函数初始化对象向量?

WiS*_*GaN 4 c++ initialization vector c++11

如何std::vector<std::ifstream>从现有的初始化 std::vector<std::string>文件的名称打开?

没有初始化vector,我可以使用它

std::vector<std::string> input_file_names;
// Populate the vector with names of files that needs to open.
// ...
std::vector<std::ifstream> input_files_;
for (auto const & input_file_name : input_file_names) {
  input_files_.emplace_back(input_file_name);
}
Run Code Online (Sandbox Code Playgroud)

she*_*heu 14

在c ++ 11中,std::ifstream构造函数将a std::string作为参数.与std::vector复制构造函数一起使用的字符串,这应该有效:

std::vector<std::string> filenames;
std::vector<std::ifstream> files(filenames.begin(), filenames.end());
Run Code Online (Sandbox Code Playgroud)

  • @sheu,chris:从std :: string到std :: ifstream的转换也是一个隐式转换,构造函数确实*被标记为显式(**§27.9.1.7,3**).但是,`vector`的范围构造函数显式调用转换,所以我错了:**§23.2.3**声明在这种情况下,`ifstream`应该是来自`string`的`EmplaceConstructible`,它来自**§23.2.1,13**因为`std :: allocator`用于目标向量. (5认同)