Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a vector of objects using both vector and the objects constructor?

How do I initialize std::vector<std::ifstream> from an existing std::vector<std::string> which are the names of the files that are intended to open?

Without an initialization of vector, I can do it using

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);
}
like image 218
WiSaGaN Avatar asked Dec 08 '22 18:12

WiSaGaN


1 Answers

In c++11, the std::ifstream constructor will take a std::string as a parameter. String that together with the std::vector copy constructor, and this should work:

std::vector<std::string> filenames;
std::vector<std::ifstream> files(filenames.begin(), filenames.end());
like image 102
sheu Avatar answered Dec 11 '22 08:12

sheu