C++ STL: Output Container Elements to Stream

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
About these ads

One thought on “C++ STL: Output Container Elements to Stream

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s