Lambda Function.

1. Definition:

[capture] (parameters) mutable exception attribute -> return_type { body }

功能上约等于:
a.函数对象(仿函数), 仿函数可存储范围更广的数据
b.局部函数

http://zh.wikipedia.org/wiki/%E5%8C%BF%E5%90%8D%E5%87%BD%E6%95%B0#C.2B.2B_11

2. Benifit:

    a. 可读性好

    b. 捕捉上下文数据

 3. Sample:

#include "stdafx.h"
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

class _F
{
    public:
        void operator()(int d) const
        { 
            cout << d << " "; 
        }

};

void Print(int n) 
{ 
    cout << n << " "; 
}

class _PreStatusF
{
public:
    _PreStatusF(int n):d(n){}
    void operator()() const
    { 
        cout << d << " "; 
    }
private:
    int d;

};

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

    for (int i = 0; i < 10; ++i) 
        v.push_back(i);

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });//1. lambda function
    cout <<endl;

    for_each(v.begin(), v.end(), Print);//2. function point
    cout <<endl;

    for_each(v.begin(), v.end(), _F()); //3. function object
    cout <<endl;
    
    _PreStatusF test(100); //function object can record the precondition.
    test();


    return 0;
}

Result:

 

posted @ 2014-08-07 13:41  anit_nait  阅读(186)  评论(0编辑  收藏  举报