版权声明:本文为博主原创文章,转载请注明源地址。 https://cloud.tencent.com/developer/article/1433467
c++11的<algorithm>
库提供了很多基础有用的模板函数。以std::copy
为例,下面的代码将容器(list)中的字符串按行输出到指定的文件,只要2行代码:
#include <algorithm>
#include <fstream>
/* 迭代器指定的字符串写入指定的文件,换行符为\n
* filename 输出文件名
* begin 起始迭代器
* end 结束迭代器
*/
template< typename inIter >
inline bool save_container_to_text(const std::string&filename, inIter begin, inIter end) {
std::ofstream fout(filename, std::ofstream::binary);
std::copy(begin, end, std::ostream_iterator<std::string>(fout, "\n"));
// 不需要显式调用open(),close(),fout创建时会自动执行open,fout对象析构时会自动执行close()函数
return true;
}
调用示例:
list<string> container;
// container 可以为list,map,vector等容器对象
save_container_to_text("output.txt", container.begin(), container.end());
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有