C++11以后版本中支持调用函数内部定义匿名lamda函数

xingyun86 2018-4-21 1636

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
    int a = 0;
    int b = 0;
    [a, b](int x, int y)
    {
        std::cout << x << ", " << y << std::endl;
    }(1, 2);
    std::cout << "Hello World! This is lamda test!" << std::endl;
    int x = 5;
    std::vector<int> c { 1,2,3,4,5,6,7 };
    c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());
    std::cout << "c: ";
    for (auto i: c)
    {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
    // the type of a closure cannot be named, but can be inferred with auto
    auto func1 = [](int i) { return i+4; };
    std::cout << "func1: " << func1(6) << std::endl;
    // like all callable objects, closures can be captured in std::function
    // (this may incur unnecessary overhead)
    std::function<int(int)> func2 = [](int i) { return i+4; };
    std::cout << "func2: " << func2(6) << std::endl;
    return 0;
}


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回