Copying to stdout using STL

The STL (Standard Template Library) is a collection of generic algorithms and data structures. This little quiz demonstrates one of the many useful things one can achieve with just a few lines of code when utilizing the power of this library.

Question: What is the output of the following code?

#include <iostream>
#include <algorithm>
#include <iterator>

struct g
{
	g():n(0){}
	int operator()() { return n++; }
	int n;
};

int main()
{
	int a[10];
	std::generate(a, a+10, g());
	std::copy(a, a+10, std::ostream_iterator<int>(std::cout, " "));
}

Answer: 0 1 2 3 4 5 6 7 8 9

Why?

The function main() uses the generate algorithm to initialise the int array using functor g. This functor will be called for every element within the array, with the result of the call used to initialise that element. Once initialised, the whole array is copied to the standard output stream using the copy algorithm.

Tip: Most of STL makes good use of functors and there are some neat reusable generic algorithms, which can be used to make code simple and easier to maintain.

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s