任何定义了函数调用操作符的对象都是函数对象。C++ 支持创建、操作新的函数对象,同时也提供了许多内置的函数对象。
运算符函数对象
C++ 针对常用的算术和逻辑运算定义了很多函数对象:
旧式绑定器与适配器
早期提供功能支持的几个工具在 C++11 中弃用,并于 C++17 中移除(旧否定器于 C++17 中弃用并于 C++20 中移除):
绑定器
将一个实参绑定到二元函数
std::bind1st,
std::bind2nd
template< class F, class T > | (1) | (C++11 中弃用) (C++17 中移除) |
template< class F, class T > | (2) | (C++11 中弃用) (C++17 中移除) |
绑定给定参数 x
到给定二元函数对象 f
的第一或第二参变量。即,在产生的包装器内存储 x
,若调用它,则将 x
传递为 f
的第一或第二参数。
1) 绑定 f
的第一参数到 x
。等效地调用 std::binder1st<F>(f, typename F::first_argument_type(x)) 。
2) 绑定 f
的第二参数到 x
。等效地调用 std::binder2nd<F>(f, typename F::second_argument_type(x)) 。
参数
f | - | 指向要绑定参数到的函数的指针 |
x | - | 绑定到 f 的参数 |
返回值
包装 f
和 x
的函数对象。
异常
(无)
调用示例
#include <iostream>
#include <algorithm>
#include <functional>
#include <cmath>
#include <vector>
const double pi = std::acos(-1);
struct myMultiplies : std::binary_function<bool, bool, bool>
{
double operator()(double a, double b)const
{
return a * b;
}
};
int main()
{
std::vector<double> vector1 = {0, 30, 45, 60, 90, 180};
std::vector<double> vector2(vector1.size());
std::vector<double> vector3(vector1.size());
std::vector<double> vector4(vector1.size());
std::vector<double> vector5(vector1.size());
std::transform(vector1.begin(), vector1.end(), vector2.begin(),
std::bind1st(std::multiplies<double>(), pi / 180.));
for (size_t index = 0; index < vector1.size(); ++index)
{
std::cout << vector1[index] << " deg = " << vector2[index] << " rad" << std::endl;
}
std::cout << std::endl;
std::transform(vector1.begin(), vector1.end(), vector3.begin(),
std::bind1st(myMultiplies(), (pi / 180.0)));
for (size_t index = 0; index < vector1.size(); ++index)
{
std::cout << vector1[index] << " deg = " << vector3[index] << " rad" << std::endl;
}
std::cout << std::endl;
std::transform(vector1.begin(), vector1.end(), vector4.begin(),
std::bind2nd(std::multiplies<double>(), pi / 180.));
for (size_t index = 0; index < vector1.size(); ++index)
{
std::cout << vector1[index] << " deg = " << vector4[index] << " rad" << std::endl;
}
std::cout << std::endl;
std::transform(vector1.begin(), vector1.end(), vector5.begin(),
std::bind2nd(myMultiplies(), (pi / 180.0)));
for (size_t index = 0; index < vector1.size(); ++index)
{
std::cout << vector1[index] << " deg = " << vector5[index] << " rad" << std::endl;
}
std::cout << std::endl;
return 0;
}
输出
0 deg = 0 rad
30 deg = 0.523599 rad
45 deg = 0.785398 rad
60 deg = 1.0472 rad
90 deg = 1.5708 rad
180 deg = 3.14159 rad
0 deg = 0 rad
30 deg = 1 rad
45 deg = 1 rad
60 deg = 1 rad
90 deg = 1 rad
180 deg = 1 rad
0 deg = 0 rad
30 deg = 0.523599 rad
45 deg = 0.785398 rad
60 deg = 1.0472 rad
90 deg = 1.5708 rad
180 deg = 3.14159 rad
0 deg = 0 rad
30 deg = 1 rad
45 deg = 1 rad
60 deg = 1 rad
90 deg = 1 rad
180 deg = 1 rad