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

1.函数指针


函数指针即函数的地址,函数的地址是存储其机器语言代码内存的开始地址。函数的地址可作为其他函数的参数。 获取函数的地址很简单 : 只要使用函数名 ( 后面不跟参数 ) 即可。也就是说,如果 think() 是一个函数,则 think 就是该函数的地址。要将函数作为参数进行传递,必须传递函数名。一定要区分传递的是函数的地址还是函数的返回值。

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值