【STL】bind1st与bind2nd函数解析

来源:互联网 发布:麻原彰晃 知乎 编辑:程序博客网 时间:2024/06/05 03:23

bind1st 和bind2nd是两个配接器
在头文件中定义。
1st代表first,2nd代表second.作用是把一个二元函数对象绑定为一个一元函数对象。STL使用bind1st和bind2nd类来自适应的将接受两个参数的函数符转换为接受一个参数的函数符,即将自适应二元函数转换为自适应一元函数。
首先看bind1st.假设有一个自适应二元函数对象f2(),则可以创建一个bind1st对象,该对象与一个将被用作f2()的第一个参数的特定值(val)相关联。
bind1st(f2,val) f1;
这样,使用单个参数调用f1(x)时,返回的值与将val作为第一参数、将f1()的参数作为第二参数调用f2()返回的值相同。即f1(x)等价于f2(val,x).
如果要将二元函数multiplies()转换为将参数乘以2.5的一元函数,可以写成下面的形式:
bind1st(multiplies() , 2.5)

#include<iostream>#include<vector>#include<iterator>#include<algorithm>#include<functional>using namespace std;void Show(double);const int LIM = 6;int main(){    double arr1[LIM] = { 28, 29, 30, 35, 38, 59 };    double arr2[LIM] = { 63, 65, 69, 75, 80, 99 };    vector<double>gr8(arr1, arr1 + LIM);    vector<double>m8(arr2, arr2 + LIM);    cout.setf(ios_base::fixed);//追加标志字的函数    cout.precision(1); cout << "gr8:\t";//固定浮点数    for_each(gr8.begin(), gr8.end(), Show);    cout << endl;    cout << "m8:\t";    for_each(m8.begin(), m8.end(), Show);    cout << endl;    vector<double>sum(LIM);    transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(), plus<double>());    cout << "sum:\t";    for_each(sum.begin(), sum.end(), Show);    cout << endl;    vector<double>prod(LIM);    transform(gr8.begin(), gr8.end(), prod.begin(), bind1st(multiplies<double>(), 2.5));//bind1st绑定,配接器    cout << "prod:\t";    for_each(prod.begin(), prod.end(), Show);    cout << endl;    return 0;}void Show(double v){    cout.width(6);    cout << v << ' ';}

结果显示:
这里写图片描述