close

 

Lambda Functions are Function Objects

 

Image for post

 

 

 

学习Lambda表达式_weixin_40747540的博客-CSDN博客_lambada 捕获生命周期

 

相關圖片

 

 

 

 

参数列表(Parameter List)
用于参数传递,这个跟普通的函数调用一样。可以传值,也可以传指针和引用。
如果你不需要传递参数,这里可以为空。
跟普通函数的差异在于:
- 不能使用默认参数
- 不能使用无名参数


捕获成员变量(Capture Clause for member variables )
设想我们有一个类MyCounter,其中有一个成员函数里面使用Lambada表达式来访问、修改某些成员变量。

捕获所有参数(by reference)
如果需要以by refenence方式捕获所有参数,只需使用[&]即可,编译器会推导使用了哪些参数,并以传引用的方式传递。

 

 

demo  
image image


    std::vector<int> vec = { 10, 20, 30, 40 };
    std::for_each(vec.begin(), vec.end(), &display);

    // 使用lambda,简化如下,不再需要display
    std::for_each(vec.begin(), vec.end(), [](int x) { std::cout << x << " "; });

 
   

// 统计vector中有多少个偶数
class MyCounter {
private:
    int counter = 0;
public:
    MyCounter() {}
    ~MyCounter() {}
    int GetCounter() { return counter; }
    void CountVec(const std::vector<int>& vec) {
        // 捕获列表,捕获this,Lambda body内即可范围该成员变量
        std::for_each(vec.begin(), vec.end(), [this](int element) {
            if (element % 2 == 0) counter++;
        });
    }
};

 

   std::vector<int> vec = { 10, 20, 30, 40, 57, 56 };

    MyCounter my;
    my.CountVec(vec);
    int n =  my.GetCounter();
    printf("\n%d, %d\n", n, my.GetCounter());

  
   

其它應用

   //..................................
    // 从vec中查找30
    auto res =
        std::find_if(vec.begin(), vec.end(), [](int elem) { return elem == 30; });
    cout << endl << "从vec中查找30 = "  << *res << endl;


    // 从vec中删除30
    auto new_end = std::remove_if(vec.begin(), vec.end(),
        [](int elem) { return elem == 30; });
    vec.erase(new_end); // 因为remove_if并没有真正删除,只是将其移动到最后了
    for (auto i : vec) {
        cout << i << " ";
    }

    // 统计vec中偶数个数
    auto count = std::count_if(vec.begin(), vec.end(),
        [](int elem) { return elem % 2 == 0; });
    cout << endl << "统计vec中偶数个数 = " <<  count; // 4

  // 按照从小到大排序
    //std::vector<int> vec = { 10, 52, 3, 7, 9, 21, 56, 6 };
    std::sort(vec.begin(), vec.end(), [](int a, int b) { return a < b; });
    cout << "小到大排序 = ";
    for (auto i : vec) {
        cout << i << " ";
    }
 

image

 

 

 

 

REF:
https://www.stevenengelhardt.com/2007/08/28/converting-c-member-functions-into-function-objects/

https://medium.com/@winwardo/c-lambdas-arent-magic-part-2-ce0b48934809

 

https://blog.csdn.net/weixin_40747540/article/details/78755742

 

arrow
arrow
    全站熱搜

    天才R 發表在 痞客邦 留言(0) 人氣()