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?
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);
}
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 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With