写在前面
在c++的早期命名中,称作仿函数(functors),但是后来采用的新名称为:函数对象(function objects),可以理解为:一种具有函数特质的对象
用处
仿函数的作用,我们在stl中经常会用到仿函数,比如:
#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int iv[] = { 1,5,9,6,3,5,7,2,10 };
vector<int> vec(iv, iv + 9);
sort(vec.begin(), vec.end());
vector<int>::iterator it = vec.begin();
for (; it != vec.end(); ++it)
cout << *it << " ";
cout << endl;
sort(vec.begin(), vec.end(), greater<int>());
it = vec.begin();
for (; it != vec.end(); ++it)
cout << *it << " ";
cout << endl;
system("pause");
}
程序中的greater<int>()就是一个仿函数。要将某种操作作为算法的参数,有两种办法,一可以将操作设计为一个函数,然后将函数的指针作为算法的一个参数,或者是将这个操作设计为一个仿函数,然后该仿函数产生一个对象,并以此作为参数
函数指针不能满足STL对抽象性的要求,并且函数指针无法和STL其他组件搭配,产生更加灵活的变化,比如在泛型的容器定义中,hash_map是根据hashtable生成的,其中利用的数据结构为:
typedef hashtable<pair<const Key, T>, Key, HashFcn,
select1st<pair<const Key, T> >, EqualKey, Alloc> ht;
ht rep;
这里的select1st<pair<const Key,T>>、HashFcn、EqualKey都是仿函数,这里仿函数使STL的组件更加灵活。
用法
我们要使用仿函数,就必须在在他定义时重载运算子operator(),这样我们就可以在仿函数对象后面使用()来调用operator()了
greater<int>()的对象原型是这样的:
template <class T>
struct greater : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const { return x > y; }
};
其中binary_function是指二元函数,但是在binary_function中什么都没有定义
仿函数有两种使用方式:使用仿函数对象直接调用operator(),而是生成临时对象调用operator()
#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
greater<int> ig;
cout << boolalpha << ig(3, 4) << endl; //方式一
cout << greater<int>()(4, 3)<<endl; //方式二greater<int>()意思是产生一个临时对象
system("pause");
}
参考书籍
《STL源码剖析》侯捷著