比较函数指针、函数符、lambda函数

        三种方法给STL算法传递信息:函数指针、仿函数、lambda

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime> // for time
using namespace std;

// 使用函数指针
bool f3(int x){
    return x%3==0;
}
bool f13(int x){
    return x%13==0;
}
// 需要一个返回bool值的可调用对象
int test1(vector<int> numbers,bool (*f)(int)){
    return count_if(numbers.begin(),numbers.end(),f);
}

// 使用仿函数
class f_mod
{
private:
    int div;
public:
    f_mod(int d=1):div(d){}
    bool operator()(int x){
        return x%div==0;
    }
};
int test2(vector<int> numbers,f_mod obj){
    return count_if(numbers.begin(),numbers.end(),obj);
}

// 使用lambda
int test3(vector<int> numbers,int d){
    if(d==3)
        return count_if(numbers.begin(),numbers.end(),[](int x){return x%3==0;});
    if(d==13)
        return count_if(numbers.begin(),numbers.end(),[](int x){return x%13==0;});
    return -1;
}

int main(){
    vector<int> numbers(1000);
    srand(time(0));
    generate(numbers.begin(),numbers.end(),rand);

    int c11=test1(numbers,f3);
    int c12=test1(numbers,f13);
    cout << "Count of numbers divisible by 3: " << c11 << endl;
    cout << "Count of numbers divisible by 13: " << c12 << endl;

    f_mod obj_3(3);
    f_mod obj_13(13);
    int c21=test2(numbers,obj_3);
    int c22=test2(numbers,obj_13);
    cout << "Count of numbers divisible by 3 using functor: " << c21 << endl;
    cout << "Count of numbers divisible by 13 using functor: " << c22 << endl;

    int c31=test3(numbers,3);
    int c32=test3(numbers,13);
    cout << "Count of numbers divisible by 3 using lambda: " << c31 << endl;
    cout << "Count of numbers divisible by 13 using lambda: " << c32 << endl;

    // 使用lambda访问变量
    int c41=0,c42=0;
    for_each(numbers.begin(),numbers.end(),[&](int x){c41+=x%3==0 ;c42+=x%13==0;});
    cout << "Count of numbers divisible by 3 using lambdas: " << c41 << endl;
    cout << "Count of numbers divisible by 13 using lambdas: " << c42 << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值