创建流向量

Create a vector of ofstreams

本文关键字:向量 创建      更新时间:2023-10-16

我正在尝试创建一个流向量。

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 添加到我的向量的最后一行正在生成错误。我忽略了什么?

如果你可以使用C++11,你可以使用std::move,如果不是只在vector中存储指针(智能指针)。

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

或与智能 PTR 一起使用

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);
}
您可以使用

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 });
}