[C++]STL-函数对象适配器

函数对象适配器是完成一些配接工作,这些配接包括绑定(bind),否定(negate),以及对一般函数或成员函数的修饰,使其成为函数对象

bind1st:将参数绑定为函数对象的第一个参数

bind2nd:将参数绑定为函数对象的第二个参数

not1:对一元函数对象取反

not2:对二元函数对象取反

ptr_fun:将普通函数修饰成函数对象

mem_fun:修饰成员函数

mem_fun_ref:修饰成员函数

绑定适配器

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<map>
#include<functional>  //使用内建函数对象,绑定适配器等需要引入该头文件
#include<algorithm>
using namespace std;




//bind1st,bind2nd 绑定适配器
//将一个二元函数对象转变为一元函数对象

struct  MyPrint : public binary_function<int, int, void>
	//要使用绑定适配器,必须继承父类,并且指明传入数据类型和返回数据类型
	//前两个参数表示传入参数数据类型,最后一个参数表示返回数据类型
{

	void operator()(int v, int w) const
	{
		cout << "v:" << v << "  val:" << w
		<< "  v + w:"<<v+w << endl;
	}
};


void test01(){
	vector<int> v;
	for (int i = 0; i < 10; i++) {
		v.push_back(i);
	}
	MyPrint print;
	int addNum = 100;
	for_each(v.begin(), v.end(), bind2nd(print,addNum));
	for_each(v.begin(), v.end(), bind1st(print, addNum));

	//for_each默认向第三个参数(仿函数)内传入一个参数
	//当我们需要向其中传入两个参数是,就需要使用绑定适配器来解决问题


	//bind1st,bind2nd区别
	//bind1st将参数绑定为函数对象第一个参数
	//bind2nd将参数绑定为函数对象第二个参数
	//两个的作用都是将二元函数对象转换为一元函数对象

}

int main() {
	test01();
	return 0;
}

取反适配器

//取反适配器 not1,not2
struct MyCompare :public binary_function<int,int ,bool>  //取反适配器也要继承基类
{
public:
	bool operator()(int v1,int v2) const{
		return v1 > v2;
	}
	
};
struct MyPrint2 {
	void operator()(int v) const
	{
		cout << "v:" << v <<endl;
	}
};

struct MyGreater : public unary_function<int, bool>  //二元都用binary ,一元都用unary
{
	bool operator()(int val)const 
	{
		return val < 45;
	}
};


void test02() {
	vector<int> v;
	for (int i = 0; i < 10; i++) {
		v.push_back(rand()%100);
	}
	for_each(v.begin(), v.end(), MyPrint2());
	cout << "-----------" << endl;
	sort(v.begin(), v.end(), MyCompare());  //按照给定规律进行排序

	for_each(v.begin(), v.end(), MyPrint2());
	cout << "-----------" << endl;

	sort(v.begin(), v.end(), not2(MyCompare()));  //对给定规律进行取反
	
	for_each(v.begin(), v.end(), MyPrint2());


	//not1和not2区别
	//对二元谓词(二元函数对象)取反用not2,对一元谓词取法用not1
	vector<int>::iterator it = find_if(v.begin(), v.end(), not1(MyGreater()));
	//find_if()函数是查找符合相应条件的值,这里是一元谓词,所以采用not1取反
	cout << (*it) << endl;
}

成员函数适配器

//成员函数适配器 mem_fun   mem_fun_ref

class Person {
public:
	Person(int age,int id):mAge(age),mId(id){}
	Person(){}
	void show() {
		cout << "年龄:" << this->mAge << "  ID:" << this->mId << endl;
	}
	int mAge;
	int mId;
};
void test04() {
	//如果容器中存放的是对象或对象指针
	//在运行for_each 算法打印的时候,可以调用类自己提供的打印函数
	vector<Person> v;
	Person p1(10, 20), p2(23, 59), p3(18, 44);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	for_each(v.begin(), v.end(), mem_fun_ref(&Person::show));  
	//格式为: mem_fun_ref(&类名::成员方法)
	

	vector<Person*> v1;
	v1.push_back(&p1);
	v1.push_back(&p2);
	v1.push_back(&p3);
	//当容器内元素数据格式为指针时,使用mem_fun
	cout << "----------------" << endl;
	for_each(v1.begin(), v1.end(), mem_fun(&Person::show));

}
发布了18 篇原创文章 · 获赞 2 · 访问量 217

猜你喜欢

转载自blog.csdn.net/renboyu010214/article/details/104429001