c++11:std::copy示例

版权声明:本文为博主原创文章,转载请注明源地址。 https://blog.csdn.net/10km/article/details/84709909

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

猜你喜欢

转载自blog.csdn.net/10km/article/details/84709909
今日推荐