我正在尝试创建一个流媒体的矢量..
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);
}此代码将无法编译..特别是,我尝试将ofstream添加到向量的最后一行生成了一个错误。我忽略了什么?
发布于 2015-03-12 16:13:04
如果你可以使用C++11,你也可以使用std::move,如果不仅仅是在向量中存储指针(智能指针)的话。
streams.push_back(std::move(out));或使用智能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);
}发布于 2015-03-12 21:25:31
您可以使用vector::emplace_back而不是push_back,这将直接在向量中创建流,因此不需要复制构造函数:
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 });
}https://stackoverflow.com/questions/29004665
复制相似问题