Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a vector of ofstreams

Tags:

c++

ofstream

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?

like image 767
user3298872 Avatar asked Mar 12 '15 08:03

user3298872


2 Answers

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);
}
like image 123
ForEveR Avatar answered Nov 09 '22 02:11

ForEveR


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 });
}
like image 28
w.b Avatar answered Nov 09 '22 02:11

w.b