C++ 仿函数绑定适配器<functional>

本文深入探讨了C++中函数绑定的概念,包括使用`bind1st`、`bind2nd`以及`ptr_fun`来绑定普通函数和成员函数。通过实例展示了如何使用`PrintInfo2`结构体作为二元操作符,以及`mem_fun_ref`和`mem_fun`的区别。文章还涵盖了在`vector`容器上应用这些函数绑定的方法。

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

#include <vector>
#include <functional>
#include <algorithm>

using  namespace std;



//绑定函数 的参数列表是指,参数列表+返回值
struct PrintInfo2 :public binary_function<int,int,void> {
    //编译报错 具有类型“const _Fn”的表达式会丢失一些 const-volatile 限定符以调用“void PrintInfo2::operator ()(int,int)”
    //加上const
    void operator()(int value,int delt) const {
        cout << value +delt<< " ";
    }
};

void testBindFunction() {
    vector<int> v;
    for (size_t i = 5; i < 16; i++) {
        v.push_back(i);
    }
    int delt = 100;
    for_each(v.begin(), v.end(), bind1st(PrintInfo2(), delt));
}

二、ptr_fun()

该函数主要是讲函数指针或者 函数转为可调用函数对象,然后再bind1st(object) 来绑定函数对象

void handleData(int inparams,int weParams) {
	cout << " souce :" << inparams << "   setParams:" << weParams << endl;
}

//绑定函数适配器
void testBindPtr() {
	vector<int> v;
	for (size_t i = 3; i < 11; i++) {
		v.push_back(i);
	}
	//绑定 ptr_fun(handleData) 是将函数指针 变成函数对象,然后再调用bind 适配器
	
	for_each(v.begin(),v.end(),bind2nd(ptr_fun(handleData),20));
}
	

三、mem_fun_ref()和mem_fun()区别

mem_fun_ref 绑定的类型是引用类型,mem_fun 是指针类型

class Person {
public:
	Person(int age, string name) : age(age), name(name) {}
	void showInfo() {
		cout << "age: " << this->age << "   name: " << this->name.c_str() << endl;
	}
public:
	int age;
	string name;
};

void testBindField() {

	Person p1(17,"abc");
	Person p2(14,"efg");

	vector<Person>  v1;
	v1.push_back(p1);
	v1.push_back(p2);

	for_each(v1.begin(),v1.end(),mem_fun_ref(&Person::showInfo));
	cout << "--------------------------" << endl;
	vector<Person*>  v2;
	v2.push_back(&p1);
	v2.push_back(&p2);
	for_each(v2.begin(), v2.end(), mem_fun(&Person::showInfo));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值