I have just started using MSVC 10 this week and already toying with lambda functions. Here a very small example:

vector<float> out;
// fill vector 

ofstream out_file( "./result.txt" );
for_each( out.begin(), out.end()
        , [&out_file]( float f ) ->void { out_file << f << " "; });

All up to the third parameter of for_each should be familiar territory. The “[&out_file]” is passing a std::ofstream reference into the lambda function. “(float f)” is the parameter of this function and “->void” is the return type. “->void” can be omitted, I believe. Everything the “{” and “}” should be familiar grounds.

Another way to achieve the same effect is to use the “copy” algorithm with an ostream_iterator. Like this:

vector<float> out;
// fill vector 

ofstream out_file( "./result.txt" );
copy( out.begin(), out.end(), ostream_iterator<float>( out_file, " " ));

Addition: Instead of saying “[&out_file]” one could just say “[&]” which means that all variables passed into the lambda function are passed by reference.

Advertisements