Printing using std::copy

Posted on: 14/08/2009

From time to time we are required to print out a vector. It is possible to utilize the standard copy algorithm (std::copy) to do just that.

Here’s how:

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using std::copy;
using std::cout;
using std::ostream_iterator;
using std::vector;

int main () {
    vector<float> v(10, 3.14f);
    copy(v.begin(), v.end(), ostream_iterator<float>(cout, " "));
    return 0;

Quite interesting if you think this through; you are able to use the copy algorithm to copy data to an output iterator.

Are you familiar with any other original ways of implementing such a printout? You’re more than welcome to share.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 27 other followers


%d bloggers like this: