huidong

首页 | 会员登录 | 关于争取 2022 寒假做出汇东网 Ver3.0.0 !
搜索文章


https://blog.csdn.net/zhang14916/article/details/101058089


C++ 中的匿名函数通常为

[capture](parameters)->return-type{body}

当 parameters 为空的时候,() 可以被省去,当 body 只有“return”或者返回为 void,那么 "->return-type" 可以被省去,下面将将对其中的参数一一解释

    capture:

    []        //未定义变量.试图在Lambda内使用任何外部变量都是错误的.
    [x, &y]   //x 按值捕获, y 按引用捕获.
    [&]       //用到的任何外部变量都隐式按引用捕获
    [=]       //用到的任何外部变量都隐式按值捕获
    [&, x]    //x显式地按值捕获. 其它变量按引用捕获
    [=, &z]   //z按引用捕获. 其它变量按值捕获

    parameters:存储函数的参数
    return-type:函数的返回值
    body:函数体


举个例子

  我们可以将匿名函数做函数指针使用

    #include<iostream>
    void main()
    {
        int Featurea = 7;
        int Featureb = 9;
        auto fun = [](size_t Featurea, size_t Featureb){return Featurea<Featureb ? Featurea : Featureb; };
        int i = fun(Featurea, Featureb);
        std::cout << i << std::endl;
    }



    对一些STL容器函数sort,find等,其最后的一个参数时函数指针,我们也可以使用匿名函数来完成

    #include<vector>
    #include<algorithm>
    #include<iostream>
     
    void main()
    {
        std::vector<int> a(5);
        a[0] = 3;
        a[1] = 4;
        a[2] = 5;
        a[3] = 6;
        a[4] = 7;
        std::for_each(std::begin(a), std::end(a), [](int Feature){std::cout << Feature << std::endl; });
    }

    我们可以直接调用函数指针

    #include<iostream>
    template <class Callback>
    int CollectFeatures(Callback CB)
    {
        int count = 0;
        for (int i = 0; i < 10; i++)
        {
            if (CB(i))
            {
                count++;
            }
        }
        return count;
    }
    bool AddFeature(size_t Feature)
    {
        return Feature % 2;
    }
    void main()
    {
        
        int i = CollectFeatures([](size_t Feature) -> bool { return AddFeature(Feature); });
        std::cout << i << std::endl;
    }




返回首页


Copyright (C) 2018-2024 huidong