12

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?

user3298872
  • 231
  • 2
  • 10

2 Answers2

18

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);
}
ForEveR
  • 55,233
  • 2
  • 119
  • 133
11

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 });
}
w.b
  • 11,026
  • 5
  • 30
  • 49