Printing using std::copy

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