【C++】STL函数对象适配器的使用

本文介绍了C++中函数适配器(如bind1st和bind2nd)以及函数指针适配器(ptr_fun)的使用,展示了如何将单参数函数转换为多参数函数并结合自定义函数对象的状态,以实现特定功能的遍历操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1、函数适配器

        如果函数对象仅有一个输入但是需要多个输入,可采用函数适配器bind1st和bind2nd绑定要输入的参数即可,同时需要我们自己的函数对象继承binary_function(二元函数对象)或者 unary_function(一元函数对象)。

class my_Print :public binary_function<int,int,void>//<第一个参数类型,第二个参数类型,返回值>
{
    public:
        void operator()(int val1,int val2) const{
        cout << "val1= : " << val1<< " val2= :" <<val2<< " val1+val2 = :" << (val1+ val2) << endl;}
};
void test()
{
    vector<int>v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }
    cout << "请输入起始值:" << endl;
    int origin;
    cin >> origin;
    //bind1st bind2nd将二元函数对象转为一元函数对象
    for_each(v.begin(), v.end(), bind2nd(my_Print(), origin));//bind2nd将参数绑定为函数对象的第二个参数
    //for_each(v.begin(), v.end(), bind1st(my_Print(),origin));//bind1st将参数绑定为函数对象的第一个参数
}

        同时因为函数对象可以有自己的状态所以也可以在函数对象内定义成员变量,通过有参构造来进行,这就是使用函数对象的好处。

class my_Print{
    public:
        my_Print(int add):m_Add(add){};
        void operator()(int value){
        cout<<value+m_Add<<" ";
        }
    private:
        int m_Add;
};
int main(){
    int add;
    cin>>add;	
    for_each(v.begin(),v.end(),my_Print(add));
    //for_each(v.begin(), v.end(), bind2nd(my_Print(),add));
    return 0;
}

2、函数指针适配器

        函数指针适配器ptr_fun( )可以把一个普通的函数指针适配成函数对象,从而使用。

void my_Print(int val1,int val2)
{
    cout << val1 + val2<< " ";
}
void test()
{
    vector <int> v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }
    // ptr_fun( )把一个普通的函数指针适配成函数对象
    for_each(v.begin(), v.end(), bind2nd(ptr_fun(my_Print), 100));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值