TripShock
TripShock

Reputation: 4249

Vector of ifstreams

How can I create and manipulate a vector of ifstreams?

Something like this, except this doesn't work:

vector<ifstream> Files(10, ifstream());
Files[0].open("File");

Upvotes: 2

Views: 516

Answers (3)

Michel de Ruiter
Michel de Ruiter

Reputation: 7966

Since C++11, you can use emplace_back:

vector<ifstream> Files;
Files.emplace_back("File1");
// ...

// Use the files here...

// Close them afterwards:
for (auto &file : Files) file.close();

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143269

The closest I can think of is vector<shared_ptr<ifstream> > — you can't put ifstreams in vector as they're not copy-constructible.

Upvotes: 3

hrnt
hrnt

Reputation: 10142

You cannot store ifstreams in a std::vector, because you can not create copies of them.

You can accomplish something similar by storing pointers instead. In that case, I recommend you use some sort of a pointer container to make sure that those ifstreams get deleted.

Upvotes: 9

Related Questions