Archive

Archive for June, 2010

Project Euler

Have you signed up for project euler yet? I did a few days ago. Today I solved problem 66 which was the hardest one I have tried yet. A great way to waste time… 🙂

Categories: Uncategorized

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;

    vec.push_back(1);

    vec.push_back(2);

    vec.push_back(3);

    vec.push_back(4);

    vec.push_back(5);

 

    // 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