O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.11. Printing a Range to a Stream

Problem

You have a range of elements that you want to print to a stream, most likely cout for debugging.

Solution

Write a function template that takes a range or a container, iterates through each element, and uses the copy algorithm and an ostream_iterator to write each element to a stream. If you want more control over formatting, write your own simple algorithm that iterates through a range and prints each element to the stream. (See Example 7-11.)

Example 7-11. Printing a range to a stream

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

int main() {

   // An input iterator is the opposite of an output iterator: it
   // reads elements from a stream as if it were a container.
   cout << "Enter a series of strings: ";
   istream_iterator<string> start(cin);
   istream_iterator<string> end;
   vector<string> v(start, end);

   // Treat the output stream as a container by using an
   // output_iterator.  It constructs an output iterator where writing
   // to each element is equivalent to writing it to the stream.
   copy(v.begin(), v.end(), ostream_iterator<string>(cout, ", "));
}

The output for Example 7-11 might look like this:

Enter a series of strings: z x y a b c
^Z
z, x, y, a, b, c,

Discussion

A stream iterator is an iterator that is based on a stream instead of a range of elements in some container, and stream iterators allow you to treat stream input as an input iterator (read from the dereferenced value ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required