请注意标题是Functors(而不是Functions)!!
考虑仅带有一个参数的函数。当调用这个函数,并且我们有更多信息想传递给这个函数时,我们别无他法,因为它只接受一个参数。到底该怎么做呢?
一个显而易见的想法是全局变量。但是良好的编程习惯并不提倡使用全局变量,只有在没有其他方法时才必须使用。
仿函数(Functors)是可以被视为函数或函数指针的对象。仿函数最常与STL在下述这种情况下一起使用:
下面的程序使用STL中的transform()函数对数组arr[]的所有元素加1。
// A C++ program uses transform() in STL to add
// 1 to all elements of arr[]
#include <bits/stdc++.h>
using namespace std;
int increment(int x) { return (x+1); }
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
// Apply increment to all elements of
// arr[] and store the modified elements
// back in arr[]
transform(arr, arr+n, arr, increment);
for (int i=0; i<n; i++)
cout << arr[i] <<" ";
return 0;
}
输出:
2 3 4 5 6
上述代码片段只对arr数组中每个元素加了一个值。现在假设要对arr数组中每个元素加上5。
瞧瞧发生了什么?因为这里transform需要传进的参数是一元函数( unary function,只有一个变量的函数),我们不能再传一个参数给increment()。这也就需要我们对应于加不同的值而写不同的函数。真是一团糟。该是仿函数登场了。
仿函数(或函数对象)是一种类似于函数的C++类。仿函数使用相同的旧函数调用语法来调用。为了创建一个仿函数,我们需要创建一个重载了()运算符的的类。
The line, MyFunctor(10); Is same as MyFunctor.operator()(10);
让我们深入研究并了解其实际上如何与STL结合使用。
// C++ program to demonstrate working of
// functors.
#include <bits/stdc++.h>
using namespace std;
// A Functor
class increment
{
private:
int num;
public:
increment(int n) : num(n) { }
// This operator overloading enables calling
// operator function () on objects of increment
int operator () (int arr_num) const {
return num + arr_num;
}
};
// Driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int to_add = 5;
transform(arr, arr+n, arr, increment(to_add));
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
输出:
6 7 8 9 10
因此,这里increment是一个仿函数,类似于函数的一个C++类。
The line, transform(arr, arr+n, arr, increment(to_add)); is the same as writing below two lines, // Creating object of increment increment obj(to_add); // Calling () on object transform(arr, arr+n, arr, obj);
因此,重载了()运算符的对象被创建。所以,仿函数能有效地与STL结合使用。
——————
1392

被折叠的 条评论
为什么被折叠?



