函数对象function objects,又名仿函数,一种行为类似函数的对象,调用者可以向函数一样使用该对象,其实现起来也比较简单:用户只需要实现一种新类型,在类中重载operator()即可,参数根据用户所要进行的操作选择匹配。如下所示:
class FunctionObjectType
{
public:
void operator() {
statements
}
};
【例】使用仿函数实现一个冒泡排序
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T, class COM>
void BubbleSort(T* array, size_t len, COM compare)
{
bool isBool = false;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (compare(array[j], array[j + 1]))
{
swap(array[j], array[j + 1]);
isBool = true;
}
}
if (isBool == false)
{
return;
}
}
}
template<class T>
class Less
{
public:
bool operator()(T& left, T& right)
{
return left < right;
}
};
template<class T>
class Greater
{
public:
bool operator()(T& left, T& right)
{
return left > right;
}
};
int main()
{
int array[] = { 2, 1, 4, 8, 9, 6, 5, 7, 3 };
size_t len = sizeof(array) / sizeof(array[0]);
cout << "原始数据为:";
for (size_t i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
BubbleSort(array, len, Less<int>());
cout << "递增排序后的数据为:";
for (size_t i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
BubbleSort(array, len, Greater<int>());
cout << "递减排序后的数据为:";
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
运行结果为: