【问题标题】:Create a vector of ofstreams创建一个 ofstreams 向量
【发布时间】:2015-03-12 08:07:26
【问题描述】:

我正在尝试创建一个 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);
}

此代码将无法编译.. 特别是我尝试将 ofstream 添加到我的向量的最后一行正在生成错误。我忽略了什么?

【问题讨论】:

  • 这会失败,因为ofstream 没有复制构造函数。
  • 我想你可以移动一个吗?

标签: c++ ofstream


【解决方案1】:

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

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

或使用智能指针

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

【讨论】:

  • 使用std::move 有效!为我省去了很多麻烦,谢谢!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多