std::bind1st, std::bind2nd
来自 cppreference.cn
< cpp | utility | functional
定义于头文件 <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 的第一个或第二个形参传递。
目录 |
[edit] 参数
f | - | 指向要绑定实参的函数的指针 |
x | - | 要绑定到 f 的实参 |
[edit] 返回值
包装 f 和 x 的函数对象。
[edit] 异常
可能抛出实现定义的异常。
[edit] 示例
运行此代码
#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); // since C++20 use std::numbers::pi std::transform(a.begin(), a.end(), r.begin(), std::bind1st(std::multiplies<double>(), pi / 180.0)); // an equivalent lambda is: [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
[edit] 参见
(在 C++11 中弃用)(在 C++17 中移除) |
保持二元函数及其一个实参的函数对象 (类模板) |
(C++20)(C++23) |
按顺序将可变数量的实参绑定到函数对象 (函数模板) |