📅 2010-Apr-30 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ containers, cpp, stl, streams ⬩ 📚 Archive
The std::copy function (defined in <algorithm>
) can be used to easily output elements of any STL container to any ostream. To do this, we can use the std::ostream_iterator (defined in <iterator>
). std::ostream_iterator
can be passed a ostream object and an optional delimiter string.
For example to output a vector of integers to std::cout
:
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
std::vector<int> iVec;
// ...
std::copy(iVec.begin(), iVec.end(), std::ostream_iterator<int>( std::cout ));
// ...
std::copy(iVec.begin(), iVec.end(), std::ostream_iterator<int>( std::cout, "\n" )); // One integer per line