函数配接器

1. 定义:
   STL中的函数配接器,能够将函数子和另一个函数子、常数、普通函数结合起来。
   STL中的函数配接器一共有4个,分别是:
                    bind1nd(op ,value)  相当于构成op(value,param),即把value结合成op的第一个参数;
                    bind2nd(op ,value)  相当于构成op(param,value),即把value结合成op的第二个参数;
                    not1(op) 相当于构成!op(param), 即op(param)的结果进行逻辑非运算;
                    not2(op) 相当于构成!op(param,param), 即把op(param,param)的结构进行逻辑非运算。                                                                                            
                表达式                     效果
        bind1st(op,value)                      op(value,param)
        bind2nd(op,value)         op(param,value)
             not1(op)         !op(param)
             not2(op)         !op(param1,param2)       
 
2. bind2nd应用举例:
 bind2nd可以配接函数子和另一个函数子、常数和普通函数。其中,普通函数作为bind2nd的第一个参数时,要用ptr_fun封装该函数,使其变为函数子。
#include <iostream>
#include <vector>
#include <iterator>  
#include <algorithm>
#include <functional>
using namespace std;
class PlusNum :public binary_function<int,int,void>
{
public:
    void operator()(int &x,int y) const
    {
        x += y;
    }
};
void PlusInt(int x, int y)
{
    cout<< x + y<<" ";
}
int SubInt(int x, int y)
{
    return x-y;
}
int main()
{
    vector<int> vi = {1,4,6,2,5,7,9};
    //bind2nd将常数和函数子配接。常数100作为 PlusNum函数子中operator(x,y)的第二个参数 y
    for_each(vi.begin(),vi.end(),bind2nd(PlusNum(), 100) );    
    copy(vi.begin(),vi.end(),ostream_iterator<int>(cout," "));
    cout<<endl;
    
    //bind2nd将普通函数和函数子配接。函数 SubInt()的返回值作为 PlusNum函数子中operator(x,y)的第二个参数 y
    for_each(vi.begin(),vi.end(),bind2nd(PlusNum(), SubInt(1010,10)) );    
    copy(vi.begin(),vi.end(),ostream_iterator<int>(cout," "));
    cout<<endl;

    //用ptr_fun将一个函数适配成一个函数子,再用bind2nd将其与常数结合。
    for_each(vi.begin(),vi.end(),bind2nd(ptr_fun(PlusInt),1000) );        
    
    return 0;
}
原文地址:https://www.cnblogs.com/ladawn/p/8319065.html