c++ 中lambda ,函数对象

/**
 * example:生成一个随机数数组,并且判断多少能被3整除,多少能被13整除?
 * description: 用函数指针,函数符(即函数对象)和Lambda函数 给STL算法传递信息
 * compile:g++ lambda_test_01.cpp -std=c++11
 * */

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

// 1.function pointer
bool f3(int x) { return x%3 == 0;}
bool f13(int x) { return x%13 == 0;}

void using_func_pointer(vector<int>& num){
    std::cout << __FUNCTION__ << "Count of num divisible by 3 : " << std::count_if(num.begin(),num.end(),f3) << std::endl;
    std::cout << __FUNCTION__ << "Count of num divisible by 13 : " << std::count_if(num.begin(),num.end(),f13) << std::endl;
}

// 2.function_object
class function_obj{
    private:
        int dv;
    public:
        function_obj(int d = 1):dv(d){}
        bool operator()(int x) {return x%dv == 0;}  //使用函数符的优点:通过一个函数完成多项任务(3和13的整除)。
};

void using_function_pointer(vector<int>& num){
    std::cout << __FUNCTION__ << "Count of num divisible by 3 : " << std::count_if(num.begin(),num.end(),function_obj(3)) << std::endl;
    std::cout << __FUNCTION__ << "Count of num divisible by 3 : " << std::count_if(num.begin(),num.end(),function_obj(13)) << std::endl;
}

// 3.lambda
/**
 * bool f3(int x) { return x%3 == 0;} 等同于---> [] (int x) {return x%3==0;}
 **/
void using_lambda(vector<int>& num){
    std::cout << __FUNCTION__ << "Count of num divisible by 3 : " << std::count_if(num.begin(),num.end()
                                                                                    ,[] (int x) {return x%3==0;}) << std::endl;
    std::cout << __FUNCTION__ << "Count of num divisible by 3 : " << std::count_if(num.begin(),num.end()
                                                                                    ,[] (int x) {return x%13==0;}) << std::endl;    
}

int main(int argc,char** argv){

    std::vector<int> num(1000);
    std::generate(num.begin(),num.end(),std::rand);

    // for(int& v : num)
    //     std::cout << v << " ";
    // std::cout << std::endl;
    std::cout << __FUNCTION__ <<"vector num size: " << num.size() << std::endl;

    // 1.function pointer
    using_func_pointer(num);

    // 2.function_object
    // function_obj obj(3);
    using_function_pointer(num);

    // 3.lambda
    using_lambda(num);


    return 0;
}

posted @ 2021-08-13 11:17  方罗良  阅读(100)  评论(0)    收藏  举报