1.函数指针
process(think); //函数think()的地址传给process()
process(think()); //函数think()的返回值传给process()
2.函数符
函数符是可以以函数方式与()结合使用的任意对象。这包括函数名、指向函数的指针和重载了()运算符的类对象(即定义了函数operator()()的类)。函数符是一个类对象,并非只能像函数名那样使用它,这要归功于类方法operator()()。函数符的优点之一是,可使用同一个函数符来完成这两项基数任务。
例如:
class f_mod{
public:
f_mod(int d = 1) :dv(d){};
bool operator()(int x){ return x%dv == 0; }
private:
int dv;
};
则
f_mod obj(3); //f_mod.dv=3
而这个对象可使用方法operator()来返回一个bool值
bool is_div_by_3 = obj(7); //等价于obj.operator()(7)
3.lambda函数
名称lambda来自lambda calculus(λ演算),一种定义和应用函数的数学系统。这个系统让您能够使用匿名函数——即无需给函数命名。在C++11中,对于接受函数指针或函数符的函数,可以使用匿名函数定义(lambda)作为其参数。
例如:
bool f3(int i){ return i % 3 == 0; }
函数f3()对应的lambda表达式为:
[](int x){ return x % 3 == 0; }
差别有两个:1)使用[]代替了函数名(这就是匿名的由来)
2)没有声明返回类型。返回类型相当于使用decltyp根据返回值推断得到的,这里为bool。
函数指针、函数符和lambda函数code:
#include"iostream"
#include"vector"
#include"algorithm"
#include"cmath"
#include"ctime"
using namespace std;
const long Size1 = 39L;
const long Size2 = 100 * Size1;
const long Size3 = 100 * Size2;
bool f3(int i){ return i % 3 == 0; }
bool f13(int i){ return i % 13 == 0; }
int main()
{
vector<int> numbers(Size1);
srand(time(0));
generate(numbers.begin(), numbers.end(),rand);
//使用函数指针
cout << "Sample size"<<Size1<< endl;
int count3 = count_if(numbers.begin(), numbers.end(),f3);
int count13 = count_if(numbers.begin(), numbers.end(), f13);
cout << "Conut of numbers divisible by 3:" << count3 << endl;
cout << "Conut of numbers divisible by 13:" << count13 << endl;
//增加numbers的个数
numbers.resize(Size2);
generate(numbers.begin(), numbers.end(), rand);
cout << "Sample size" << Size2 << endl;
//使用函数符
class f_mod
{
public:
f_mod(int d = 1) :dv(d){};
bool operator()(int x){ return x%dv == 0; }
private:
int dv;
};
count3 = count_if(numbers.begin(), numbers.end(), f_mod(3));
count13 = count_if(numbers.begin(), numbers.end(), f_mod(13));
cout << "Conut of numbers divisible by 3:" << count3 << endl;
cout << "Conut of numbers divisible by 13:" << count13 << endl;
//增加numbers的个数
numbers.resize(Size3);
generate(numbers.begin(), numbers.end(), rand);
cout << "Sample size" << Size3 << endl;
//使用lambdas表达式
count3 = count_if(numbers.begin(), numbers.end(), [](int x){ return x % 3 == 0; });
count13 = count_if(numbers.begin(), numbers.end(), [](int x){ return x % 13 == 0; });
cout << "Conut of numbers divisible by 3:" << count3 << endl;
cout << "Conut of numbers divisible by 13:" << count13 << endl;
system("pause");
return 0;
}