流迭代器的重用
Reuse of the stream iterators
本文关键字:迭代器 更新时间:2023-10-16
我有一个文件需要在运行时多次打开。每次都会将一些文本附加到文件中。这是代码:
ofstream fs;
fs.open(debugfile, fstream::app);
ostream_iterator<double> output(fs, " ");
copy(starting_point.begin(), starting_point.end(), output);
...
fs.open(debugfile, fstream::app);
ostream_iterator<double> output1(fs, " ");
copy(starting_point.begin(), starting_point.end(), output1);
我的问题是,每次打开文件时,我是否可以使用一个流迭代器"输出",例如某种清理方法?
感谢
您可以使用以下代码:
ofstream fs;
fs.open(debugfile, fstream::app);
ostream_iterator<double> output(fs, " ");
copy(starting_point.begin(), starting_point.end(), output);
...
fs.open(debugfile, fstream::app);
output = ostream_iterator<double>(fs, " ");
copy(starting_point.begin(), starting_point.end(), output1);
这里使用相同的变量output
来存储迭代器,但迭代器本身是从头开始创建的,并使用operator =
分配给该变量。
对我来说,没有什么可以做的(apprt重新分配值)来解决您的问题。
只是不要忘记在重新打开流之前关闭并清除它:
std::ofstream file("1");
// ...
file.close();
file.clear(); // clear flags
file.open("2");
from:C++我可以重用fstream来打开和写入多个文件吗?
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?