A previous post showed a code snippet for dumping the contents of an STL container using an ostream_iterator. Things have now gotten a little bit easier with the introduction of lambda functions into the upcoming C++0x standard. Lambda functions allow pieces of code to be passed around as if they were ordinary objects. Applying lambda functions for dumping the contents of an STL container gives:
vector
generate(v.begin(), v.end(), rand);
for_each(v.begin(), v.end(),
[](int& x){ cout << x << " "; })
[/sourcecode]
OK, so the syntax looks a bit strange at first, but it does add a powerful construct to the language.
Lambdas have only just been added to the C++0x standard and support for lambdas are not included in the beta version of the Visual Studio 2008 TR1 feature pack.
For more details and examples of lambda functions, check out Herb Sutter’s recent trip report from the February/March ISO C++ standards meeting.