std::bind1st, std::bind2nd
来自 zh.cppreference.net
| 定义于头文件 <functional>
|
||
template< class F, class T >
std::binder1st<F> bind1st( const F& f, const T& x );
|
(1) | (C++11 弃用) (C++17 移除) |
template< class F, class T >
std::binder2nd<F> bind2nd( const F& f, const T& x );
|
(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 <algorithm> #include <cmath> #include <cstddef> #include <functional> #include <iomanip> #include <iostream> #include <vector> int main() { std::vector<double> a = {0, 30, 45, 60, 90, 180}; std::vector<double> r(a.size()); const double pi = std::acos(-1); // 自 C++20 起可使用 std::numbers::pi std::transform(a.begin(), a.end(), r.begin(), std::bind1st(std::multiplies<double>(), pi / 180.0)); // 等效的 lambda 表达式为:[pi](double a) { return a * pi / 180.0; }); for (std::size_t n = 0; n < a.size(); ++n) std::cout << std::setw(3) << a[n] << "° = " << std::fixed << r[n] << " rad\n" << std::defaultfloat; }
输出:
0° = 0.000000 rad 30° = 0.523599 rad 45° = 0.785398 rad 60° = 1.047198 rad 90° = 1.570796 rad 180° = 3.141593 rad
参见
|
(C++11 中弃用)
(C++17 中移除)
|
持有二元函数及其一个参数的函数对象
(类模板) |
|
(C++20)
(C++23)
|
按顺序绑定可变数量的参数到函数对象
(函数模板) |