三种方法给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;
}