美文网首页
Lambda表达式

Lambda表达式

作者: 赵伯舟 | 来源:发表于2018-08-16 16:32 被阅读11次

Lambda表达式是C++11的新特性,是一种匿名函数,一般用于小型的函数,比如:

#include <iostream>
#include <algorithm>
 
void display(int a)
{
    std::cout<<a<<" ";
}
int main() {
    int arr[] = { 1, 2, 3, 4, 5 };
    std::for_each(arr, arr + sizeof(arr) / sizeof(int), &display);
    std::cout << std::endl;
}

上面是使用函数指针输出一个数组的所有元素,如果使用Lambda表达式,则可:

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = { 1, 2, 3, 4, 5 };
    std::for_each(arr, arr + sizeof(arr) / sizeof(int), [](int x) {
            std::cout<<x<<" ";
        });
    std::cout << std::endl;
}

这样看起开就比较简练。

一、Lambda表达式基本形式

[](param) -> return_value{
        code...
}

其中[]里是捕捉的参数,()内是函数的参数,->后面是函数的返回值,一般可以省略,Lambda表达式会自动推导。

二、Lambda表达式捕捉变量

[]用于捕捉当前上下文的变量,比如:

#include <iostream>
#include <string>
 
int main(int argc, char **argv)
{
    std::string msg = "Hello";
    int counter = 10;

    //按值传递两个参数msg,counter
    auto func = [msg, counter]  () mutable {
        std::cout<<"Inside Lambda :: msg = "<<msg<<std::endl;
        std::cout<<"Inside Lambda :: counter = "<<counter<<std::endl;

        msg = "Temp";
        counter = 20;
 
        std::cout<<"Inside Lambda :: After changing :: msg = "<<msg<<std::endl;
        std::cout<<"Inside Lambda :: After changing :: counter = "<<counter<<std::endl;
 
        };

    //调用匿名函数
    func();
 
    std::cout<<"msg = "<<msg<<std::endl;
    std::cout<<"counter = "<<counter<<std::endl;
 
    return 0;
}

而按引用传值的形式如下:

auto func = [&msg, &counter] () {
  //...
 };

此外:

  • [=]表示捕捉所有上下文变量,并按值传递
  • [&]表示捕捉所有上下文变量,并引用传递
    当然也可以混合传递:
auto func = [=, &counter] () mutable {};

三、Lambda表达式捕捉类的成员变量

假如类的成员函数用到类的成员变量,则需要捕捉this指针:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
 
class OddCounter
{
    int mCounter = 0;
public:
    int getCount()
    {
        return mCounter;
    }
    void update(std::vector<int> & vec)
    {
        // this is captured by value inside lambda
        std::for_each(vec.begin(), vec.end(), [this](int element){
            if(element % 2)
                mCounter++; // Accessing member variable from outer scope
        });
    }
};

相关文章

网友评论

      本文标题:Lambda表达式

      本文链接:https://www.haomeiwen.com/subject/bblobftx.html