C ++中的函子

函子是C ++中的函数对象。该函子允许某个类的实例对象被调用,就好像它是一个普通函数一样。让我们考虑一个带有一个参数的函数。我们可以将此函数用作函数对象来对一组数据执行某些任务。

范例程式码

#include <iostream>
#include <algorithm>
using namespace std;
int square(int x) {
   return x*x; //return square of x
}
int main() {
   int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
   transform(data, data+10, data, square);
   for (int i = 0; i<10; i++)
      cout << data[i] << endl;
}

输出结果

0
1
4
9
16
25
36
49
64
81