创建流向量
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);
}
这段代码不会编译......特别是我尝试将 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 });
}
相关文章:
- 从具有自定义排序的向量创建集合
- 我正在寻找一种优雅的方式来从元组向量创建tuple_element向量
- 从类指针的向量创建成员变量的向量
- 从 c++ 中的字符串向量创建一个元组
- 如何在 c++ 中从两个向量创建 JSON 对象?
- 如何在不迭代的情况下从string_view向量创建字符串向量?
- 通过移动从两个向量创建元组向量
- 为结构的向量创建C 矢量迭代器
- C 矢量元素擦除与新向量创建
- 使用向量的向量创建一个尺寸
- C MultiSet从排序的向量创建
- 从向量<T>创建一组字符串
- 使用C 中的向量创建整数集类别
- 从两个原始向量创建一个“特征::矩阵”
- 用向量创建筛子
- 从Vectores的向量创建一个板
- C++内存管理:从函数中的向量创建一个新数组
- 正在使用类中的向量创建类
- 为向量创建临时变量
- 如何在c++中使用模板图类中的向量创建邻接矩阵