1. 程式人生 > >c++11:std::copy示例

c++11:std::copy示例

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