Home > Uncategorized > Lambda expressions in C++ for Visual Studio 2010

Lambda expressions in C++ for Visual Studio 2010

I was very pleased to see that lamda expressions are now also available in C++. Lambda expressions comes very handy when using functions from the standard library such as for_each, remove_if, copy_if and many more. Here is a small sample:

#include "stdafx.h"

#include <vector>

#include <algorithm>

#include <iostream>

#include <iterator>


using namespace std;


int _tmain(int argc, _TCHAR* argv[])


    // create sample data

    vector<int> vec;







    // output iterator to stdout

    ostream_iterator<int> os(cout, "\n");


    // for_each using lambda

    cout << "All numbers" << endl;

    for_each(vec.begin(), vec.end(), [](int n) { cout << n << endl; });


    // simple lambda for even numbers

    cout << "Even numbers" << endl;

    copy_if(vec.begin(), vec.end(), os, [](int n) { return n % 2 == 0; });


    // lambda that captures variables

    const int min = 2;

    const int max = 4;

    cout << "Numbers that are greater or equal to " << min << " and less than or equal to " << max << endl;

    copy_if(vec.begin(), vec.end(), os, [min, max](int n) { return n >= min && n <= max; });


    return 0;



For more information about lambdas and other new features in C++ for Visual Studio 2010 please refer to this page. It should be noted that the boost lambda library can be used to ‘emulate’ lambda expressions in earlier versions of C++.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: