user3298872
user3298872

Reputation: 231

Create a vector of ofstreams

I'm trying to create a vector of ofstreams..

vector<ofstream> streams;
for (int i = 0; i < numStreams; i++){
  ofstream out;
  string fileName = "text" + to_string(i) + ".txt";
  output.open(fileName.c_str());
  streams.push_back(out);
}

This code will not compile.. specifically the last line where I attempt to add the ofstream to my vector is generating an error. What am I overlooking?

Upvotes: 12

Views: 7423

Answers (2)

w.b
w.b

Reputation: 11228

You can use vector::emplace_back instead of push_back, this will create the streams directly in the vector so the copy constructor is not needed:

std::vector<std::ofstream> streams;

for (int i = 0; i < numStreams; i++)
{
    std::string fileName = "text" + std::to_string(i) + ".txt";
    streams.emplace_back(std::ofstream{ fileName });
}

Upvotes: 11

ForEveR
ForEveR

Reputation: 55887

If you can use C++11 you can use std::move, if not just store pointers (smart pointers) in vector.

streams.push_back(std::move(out));

or with smart ptrs

vector<std::shared_ptr<ofstream> > streams;
for (int i = 0; i < numStreams; i++){
  std::shared_ptr<ofstream> out(new std::ofstream);
  string fileName = "text" + to_string(i) + ".txt";
  out->open(fileName.c_str());
  streams.push_back(out);
}

Upvotes: 18

Related Questions