//函数对象:
重载函数调用操作符的类, 其对象常称为函数对象(function object), 即它们是行为类
似函数的对象。 一个类对象, 表现出一个函数的特征, 就是通过“对象名+(参数列表)”的方式
使用一个类对象, 如果没有上下文, 完全可以把它看作一个函数对待。
这是通过重载类的 operator()来实现的。
“在标准库中, 函数对象被广泛地使用以获得弹性”, 标准库中的很多算法都可以使用函数
对象或者函数来作为自定的回调行为
// 函数对象:可以像函数一样使用的对象
// 一元函数对象:参数只有一个
// 二元函数对象:参数有两个
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 算法
void print(int num)
{
cout << num << " ";
}
class Show
{
public:
Show()
{
sum = 0;
}
void operator()(int num)
{
cout << num << " ";
sum += num;
}
public:
int sum;
};
// 函数对象:可以像函数一样使用的对象
// 一元函数对象:参数只有一个
// 二元函数对象:参数有两个
void func()
{
vector<int> v;
for (int i = 0; i < 10; i++)
v.push_back(i);
/*
* for (it = v.begin(); it != v.end(); it++)
* {
* XXX(*it);
* }
*/
for_each(v.begin(), v.end(), print);
cout << endl;
Show s;
s = for_each(v.begin(), v.end(), s);
cout << endl;
cout << s.sum << endl;
}
int main()
{
func();
return 0;
}
运行结果是
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
45
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(int num)
{
cout << num << " ";
}
int add(int a, int b)
{
return a+b;
}
class Mul
{
public:
int operator()(int a, int b)
{
return a*b;
}
};
// 二元函数对象
void func()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
vector<int> v2;
v2.push_back(4);
v2.push_back(5);
v2.push_back(6);
vector<int> v3(3);
/*
* for (it1 = v1.begin(), it2 = v2.begin(), it3 = v3.begin(); it1 != v1.end(); it1++, it2++, it3++)
* {
* *it3 = XXX(*it1, *it2);
* }
*/
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), add);
for_each(v3.begin(), v3.end(), print);
cout << endl;
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), Mul());
for_each(v3.begin(), v3.end(), print);
cout << endl;
}
int main()
{
func();
return 0;
}
运行结果
5 7 9
4 10 18