Printing using std::copy

August 14th, 2009 § Leave a Comment

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.

Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading Printing using std::copy at 0x.

meta