C++中的Lambda

参考:C++ Primer Plus 中文版 第六版

例子代码:

#include <iostream>
#include <vector>
#include <string>  //std::to_string
#include <algorithm> //包括了#include <cstdlib>
#include <ctime>


using namespace std;

bool f3(int x){return x%3 == 0;}
bool f13(int x){return x%13 == 0;}

int main()
{


    vector<int> arr1(100);


    std::srand(std::time(0));
    std::generate(arr1.begin(), arr1.end(), std::rand);
    //using function pointer
    int counter3 = std::count_if(arr1.begin(), arr1.end(), f3);
    int counter13 = std::count_if(arr1.begin(), arr1.end(), f13);
    cout << counter3 << " " << counter13 << endl;

    //使用函数对象 using functor
    class f_mod
    {
        int div;
    public:
        f_mod(int div=1):div(div){}
        bool operator()(int x) {return x%div == 0;}
    };
    counter3 = counter13 = 0;
    counter3 = std::count_if(arr1.begin(), arr1.end(), f_mod(3));
    counter13 = std::count_if(arr1.begin(), arr1.end(), f_mod(13));
    cout << counter3 << " " << counter13 << endl;

    //使用 Lambda 表达式  using Lambda
    counter3 = counter13 = 0;
    counter3 = std::count_if(arr1.begin(), arr1.end(), [](int x){return x%3 == 0;});
    counter13 = std::count_if(arr1.begin(), arr1.end(), [](int x){return x%13 == 0;});
    cout << counter3 << " " << counter13 << endl;
    //Lambda表达式
    counter3 = counter13 = 0;
    auto mod3 = [](int x){return x%3 == 0;};
    auto mod13 = [](int x){return x%13 == 0;};
    counter3 = std::count_if(arr1.begin(), arr1.end(), mod3);
    counter13 = std::count_if(arr1.begin(), arr1.end(), mod13);
    cout << counter3 << " " << counter13 << endl;
    //Lambda 传引用
    counter3 = counter13 = 0;
    for_each(arr1.begin(), arr1.end(), [&counter3](int x){counter3 += (x%3 == 0);});
    for_each(arr1.begin(), arr1.end(), [&counter13](int x){counter13 += (x%13 == 0);});
    cout << counter3 << " " << counter13 << endl;
    counter3 = counter13 = 0;
    for_each(arr1.begin(), arr1.end(), [&](int x){counter3 += (x%3 == 0); counter13 += (x%13 == 0);});
    cout << counter3 << " " << counter13 << endl;


//    vector<int> arr1(7);
//    vector<int> arr2(7);
//    vector<int> arr3(7);
//
//    cout << endl;
//    cout << "arr1:\t";
//    for_each(arr1.begin(), arr1.end(),
//        [](int x){std::cout.width(6); std::cout << x << ' ';}
//    );
//    cout << endl;
//    cout << "arr2:\t";
//    for_each(arr2.begin(), arr2.end(),
//        [](int x){std::cout.width(6); std::cout << x << ' ';}
//    );
//    cout << endl;
//    cout << "arr3:\t";
//    for_each(arr3.begin(), arr3.end(),
//        [](int x){std::cout.width(6); std::cout << x << ' ';}
//    );

    return 0;
}
View Code

 

posted @ 2022-04-24 16:52  htj10  阅读(22)  评论(0编辑  收藏  举报
TOP