www.flickr.com

Thursday, October 26, 2006

C++ Tip: Stream Iterators

Problem
Write an item n times to an output stream

Solution A: Write a for loop

data_type x = value
for (unsigned int i = 0; i > n; ++i)
  std::cout << x;

Solution B: Use an iterator and an algorithm
std::fill_n(std::ostream_iterator<data_type>(std::cout), n, x);

Discussion
Solution A has the advantage of simplicity. Almost everyone can remember how to code a for loop. However, Solution B serves as a neat, albeit somewhat trivial, example of the use of a stream iterator working with an algorithm. This is a powerful combination that is rarely explored. So, next time there's something interesting to be done with streams, remember that there is a lot of potential in using the algortihms in the standard library.

Addendum
I ran some tests to see how the performance of the two solutions compare. With g++ 3.4.2 (mingw-special), there's no difference, regardless of the optimisation options. So, do not hesitate to use the standard library for fear of poor performance.

No comments:

Post a Comment