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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP