是否可以使用std :: map处理std :: ofstream?

编程入门 行业动态 更新时间:2024-10-28 07:33:38
本文介绍了是否可以使用std :: map处理std :: ofstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在c ++中处理文件映射说不,应该使用 std :: map< std :: string,std :: ofstream *> ,但这会导致 new 和 delete 操作,这并不是那么整齐。

"Handling map of files in c++" says no, one shall use std::map<std::string, std::ofstream*>, but this leads to the new and delete actions, which is not so neat.

由于 std :: ofstream是否可移动??这样一来,您就不必担心关闭文件流和删除来释放内存了。

Since "Is std::ofstream movable? Yes!" and it's possible to "std::map<>::insert using non-copyable objects and uniform initialization", is it possible to handle a collection of ofstream using std::map? so that one won't worry about closing filestreams and delete to release memory.

我可以在使用过程中妥协这一点 std :: map< std :: string,std :: ofstream> ,仅创建,使用(写)并关闭,而不是复制。

I can compromise that during using std::map<std::string, std::ofstream>, only create, use (it to write) and close, not to copy it.

推荐答案

是的。参见下面的示例代码。

Yes it is possible. See sample code below.

我可以在使用 std :: map< std :: string,std的过程中妥协这一点:: ofstream> ,仅创建,使用(写)并关闭(而不是复制)。

I can compromise that during using std::map<std::string, std::ofstream>, only create, use (it to write) and close, not to copy it.

它们不可复制,因此在您的最终评论中,您是正确的,将无法复制它。

They are not copyable, so in your final comment, you are correct, you will be unable to copy it. You can move assign though, if that's what you want to do.

#include <iostream> #include <fstream> #include <map> int main() { std::map<std::string, std::ofstream> map; map.emplace("foo", std::ofstream("/tmp/foo")); map.emplace("bar", std::ofstream("/tmp/bar")); map["foo"] << "test"; map["foo"].flush(); std::ifstream ifs("/tmp/foo"); std::string data; ifs >> data; std::cout << data << '\n'; return 0; }

输出:

test

test

更多推荐

是否可以使用std :: map处理std :: ofstream?

本文发布于:2023-05-27 09:55:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285725.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   std   ofstream   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!