25 仿函数与函数对象

1、仿函数Functor的结构

在C++的STL结构中,仿函数是为了算法服务的。也就是说设计某个算法时,如sort()。会使用相关的仿函数在实现排序,而且仿函数有特定的继承结构。

template<class T>
struct plus :public binary_function<T,T,T>
{
	T operator()(const T& x, const T& y) const
	{
		return x + y;
	}
};
解析:

a、使用模板函数来设计function object,其中会继承binary_function或unary_function;

b、使用operator()操作符重载后,可以将plus类当做函数使用,这在之前篇章有介绍。使用如下:

plus<int> p;
int result = p(2, 3);
cout << result << endl; //5
说明:当使用p(2,3)是会调用重载函数operator()进行计算。

其中父类继承结构如下

template <typename arg, typename result>
struct unary_function{
	typedef arg argument_type;
	typedef result result_type;
};

template <typename arg1, typename arg2, typename result>
struct binary_function{
	typedef arg1 first_argument_type;
	typedef arg2 second_argument_type;
	typedef result result_type;
};
解析:

a、父类结构binary_function或unary_function中都没有具体的数据定义,只有一些typedef;

b、binary_function是针对仿函数是有两个参数的,模板参数分别代表第一参数类型,第二参数类型和返回值类型;

c、unary_function是针对仿函数是有一个参数的,模板参数分别代表参数类型和返回值类型。

d、这个没有任何实际参数的定义作用其实是为了确定该仿函数是否可被适配的adaptable,也就是说能否被适配器使用。类似于迭代器中设计5个原则来回答算法的提问一样。

2、仿函数的使用

仿函数一般都是通过算法来使用的,如less仿函数被sort()排序算法使用:

template<class T>
struct less :public binary_function<T, T, bool>
{
	bool operator()(const T& x, const T& y) const
	{
		return x < y;
	}
};

算法sort()使用:

vector<int> v{ 15, 37, 94, 50, 73, 58, 28, 98 };
::sort(v.begin(), v.end(), less<int>());

for (auto i : v){
	cout << i << " "; //15 28 37 50 58 73 94 98
}
cout << "\n";
解析:通过对仿函数对象的调用,实现sort()从小到大排序。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值