C++中使用lambda表达式

c++ 0x新特性(一)lambda表达式:

// LambdaException.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <ostream>
#include <vector>
#include <algorithm>

using namespace std;

struct LambdaFunction
{
    void operator()(int n) const
    {
        cout << n;
        if(n%2 == 0)
        {
            cout << " even ";
        }
        else
        {
            cout << " odd ";
        }
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> vint;

    for(int i = 0; i<8; i++)
    {
        vint.push_back(i);
    }
    //lambda(方法一)
    /*for_each(vint.begin(),vint.end(),[](int n)
    {
        cout << n;
        if(n % 2 == 0 )
        {
            cout << " even ";
        }
        else
        {
            cout << " odd ";
        }
    });*/
    //lambda(方法二)
    for_each(vint.begin(), vint.end(), LambdaFunction());
    cout << endl;
    return 0;
}
posted @ 2012-05-03 00:00  lmy4710  阅读(79)  评论(0)    收藏  举报