C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++11 lambda 包装器

C++11新特性之lambda、包装器详解

作者:雾岛听蓝

lambda表达式是一种匿名函数对象,可以定义在函数内部,用于定义轻量级的局部小函数,本文给大家介绍C++11新特性之lambda、包装器的相关知识,感兴趣的朋友跟随小编一起看看吧

lambda

lambda表达式语法

int main()
{
    //一个简单的lambda表达式
    auto add1 = [](int x, int y)->int
        {
            return x + y;
        };
    cout << add1(1, 2) << endl; //3
    //1.捕捉为空也不能省略
    //2.参数为空可以省略
    //3.返回值可以省略,可以通过返回对象自动推导
    //4.函数体不能省略
    auto func1 = []  //省略参数、返回类型
        {
            cout << "hello ssp" << endl;
            return 0;
        };
    func1();    //hello ssp
    int a = 0, b = 1;
    auto swap1 = [](int& x, int& y)  //省略返回类型
        {
            int tmp = x;
            x = y;
            y = tmp;
        };
    swap1(a, b);
    cout << a << ":" << b << endl;  //1:0
    return 0;
}

捕捉列表

int x = 0;
//定义在全局捕捉列表必须为空,因为全局变量不用捕捉就可以用,没有可捕捉的变量
auto func1 = []()
    {
        x++;
    };
int main()
{
    //只能用当前lambda局部域和捕捉的对象和全局对象
    int a = 0, b = 1, c = 2, d = 3;
    auto func1 = [a, &b]    //除了类域,都是向上查找
        {
            //值捕捉的变量不能修改,引用捕捉的变量可以修改
            //a++ //错误
            b++; //会影响外面的b
            int ret = a + b;
            return ret;
        };
    cout << func1() << endl;    //2
    //隐式值捕捉
    //用了哪些变量就捕捉哪些变量
    auto func2 = [=]()
        {
            int ret = a + b + c;
            return ret;
        };
    cout << func2() << endl;    //4
    //隐式引用捕捉
    //用了哪些变量就捕捉哪些变量
    auto func3 = [&]
        {
            a++;
            c++;
            d++;
        };
    func3();
    cout << a << " " << b << " " << c << " " << d << endl;
    //1 2 3 4
    //混合捕捉1
    auto func4 = [&, a, b]
        {
            //a++;
            //b++;
            c++;
            d++;
            return a + b + c + d;
        };
    func4();
    cout << a << " " << b << " " << c << " " << d << endl;
    //1 2 4 5
    //混合捕捉2
    auto func5 = [=, &a, &b]
        {
            a++;
            b++;
            //c++;
            //d++;
            return a + b + c + d;
        };
    func5();
    cout << a << " " << b << " " << c << " " << d << endl;
    //2 3 4 5
    //局部的静态和全局变量不能捕捉,也不需要捕捉
    static int m = 0;
    auto func6 = []
        {
            int ret = x + m;
            return ret;
        };
    //传值捕捉本质是一种拷贝,并且被const修饰了
    //mutable相当于去掉const属性,可以修改了
    //但是修改不会影响外面被捕捉的值,因为是一种拷贝
    auto func7 = [=]()mutable
        {
            a++;
            b++;
            c++;
            d++;
            return a + b + c + d;
        };
    cout << func7() << endl;    //18
    cout << a << " " << b << " " << c << " " << d << endl;
    //3 4 5 6
    return 0;
}

lambda应用

struct Goods
{
    string _name;   //名字
    double _price;  //价格
    int _evaluate;  //评价
    Goods(const char* str, double price, int evaluate)
        :_name(str)
        , _price(price)
        , _evaluate(evaluate)
    {}
};
struct ComparePriceLess
{
    bool operator()(const Goods& gl, const Goods& gr)
    {
        return gl._price < gr._price;
    }
};
struct ComparePriceGreater
{
    bool operator()(const Goods& gl, const Goods& gr)
    {
        return gl._price > gr._price;
    }
};
int main()
{
    vector<Goods> v = { { "苹果", 2.1, 5 }, { "⾹蕉", 3, 4 }, 
    { "橙⼦", 2.2, 3 }, { "菠萝", 1.5, 4 } };
    //类似这样的场景,我们实现仿函数对象或者函数指针支持不同项的比较
    //相对还是比较麻烦的,不写注释也方便理解,那么用lambda就很好用了
    sort(v.begin(), v.end(), ComparePriceLess());
    sort(v.begin(), v.end(), ComparePriceGreater());
    sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
        return g1._price < g2._price; 
        });
    sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
        return g1._price > g2._price;
        });
    sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
        return g1._evaluate < g2._evaluate;
        });
    sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
        return g1._evaluate > g2._evaluate;
        });
    return 0;
}

lambda的原理

包装器

function

#include <functional>
int f(int a, int b)
{
    return a + b;
}
struct Functor
{
public:
    int operator()(int a, int b)
    {
        return a + b;
    }
};
class Plus
{
public: 
    Plus(int n=10)
        :_n(n)
    { }
    static int plusi(int a, int b)
    {
        return a + b;
    }
    double plusd(double a, double b)
    {
        return (a + b) * _n;
    }
private:
    int _n;
};
int main()
{
    //包装各种可调用对象,需要参数类型匹配
    function<int(int, int)> f1 = f; //第一个int是返回值类型,(int.int)为参数列表
    function<int(int, int)> f2 = Functor();
    function<int(int, int)> f3 = [](int a, int b) {return a + b; };
    cout << f1(1, 1) << endl;
    cout << f2(1, 1) << endl;
    cout << f3(1, 1) << endl;
    //包装静态成员函数
    //成员函数要指定类域并且前面加&才能获取地址
    //&静态的可加可不加,非静态的必须加&
    function<int(int, int)> f4 = &Plus::plusi;
    cout << f4(1, 1) << endl;
    //包装普通成员函数
    //普通成员函数还有一个隐含的this指针参数,
    //所以绑定时要传对象或者对象的引用或指针过去
    function<double(Plus*, double, double)> f5 = &Plus::plusd;
    Plus pd;    //是用传入的对象去调用函数
    cout << f5(&pd, 1.1, 1.1) << endl;
    function<double(Plus, double, double)> f6 = &Plus::plusd;
    cout << f6(pd, 1.1, 1.1) << endl;
    function<double(Plus&&, double, double)> f7 = &Plus::plusd;
    cout << f7(move(pd), 1.1, 1.1) << endl; //用右值引用
    cout << f7(Plus(), 1.1, 1.1) << endl;   //用匿名对象
    return 0;
}

bind

class Plus
{
public: 
    Plus(int n=10)
        :_n(n)
    { }
    static int plusi(int a, int b)
    {
        return a + b;
    }
    double plusd(double a, double b)
    {
        return (a + b) * _n;
    }
private:
    int _n;
};
int main()
{
    auto sub1 = bind(Sub, _1, _2);
    cout << sub1(10, 5) << endl;    //50
    //bind本质是返回的一个仿函数对象
    //调整参数顺序(不常用)
    //_1表示第一个实参
    //_2表示第二个实参
    //……
    auto sub2 = bind(Sub, _2, _1);
    cout << sub2(10, 5) << endl;    //-50
    //调整参数个数(常用)
    auto sub3 = bind(Sub, 100, _1); //把a固定为100
    cout << sub3(3) << endl;    //970
    auto sub4 = bind(Sub, _1, 100); //把b固定为100
    cout << sub4(3) << endl;    //-970
    //分别绑死第123个参数
    auto sub5 = bind(SubX, 100, _1, _2);    //100-_1-_2
    cout << sub5(5, 1) << endl;
    auto sub6 = bind(SubX, _1, 100, _2);    //_1-100-_2
    cout << sub6(5, 1) << endl;
    auto sub7 = bind(SubX, _1, _2, 100);    //_1-_2-100
    cout << sub7(5, 1) << endl;
    //成员函数对象进行绑死,就不需要每次传递了
    function<double(Plus&&, double, double)> f6 = &Plus::plusd;
    Plus pd;
    cout << f6(move(pd), 1.1, 1.1) << endl;
    cout << f6(Plus(), 1.1, 1.1) << endl;
    //bind一般用于绑死一些固定参数
    function<double(double, double)> f7 = bind(&Plus::plusd, Plus(), _1, _2);
    cout << f7(1.1, 1.1) << endl;
    return 0;
}

到此这篇关于C++11新特性之lambda、包装器详解的文章就介绍到这了,更多相关C++11 lambda 包装器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文