C++适配器简单介绍

绑定适配器:

struct Myprint:public binary_function<int,int,void>
{
	void operator()(int v,int val)const
	{
cout << "v:" << v << " " << "val:" << val << " " << "(v + val):" << v + val << endl;
	}
};

void main01()//绑定适配器
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	for_each(v.begin(), v.end(), bind1st(Myprint(), 200));
	//将一个二元函数对象转换成一元函数对象
	//bind1st将200绑定为函数对象的第一个参数
	//bind2nd将200绑定为函数对象的第一个参数
}

仿函数适配器  not1 not2取反适配器:

struct MyCompare :public binary_function<int, int, void>
{
	bool operator()(int val1, int val2)const
	{
		return	val1 < val2;
	}
};

struct Myprint02
{
	void operator()(int v)
	{
		cout << v << ends;
	}
};

struct MyCompare02:public unary_function<int,bool>
{
	bool operator()(int val1)const
	{
		return	val1 > 10;
	}
};

void main02()//仿函数适配器  not1 not2取反适配器
{
	vector<int>v1;
	srand(time(0));
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(rand()%100);
	}
	for_each(v1.begin(), v1.end(), Myprint02()); 
	cout << endl;
	sort(v1.begin(), v1.end(),not2( MyCompare()));
	for_each(v1.begin(), v1.end(), Myprint02());
	cout << endl;
	vector<int>::iterator it = find_if(v1.begin(), v1.end(), not1(MyCompare02()));
	for_each(v1.begin(), v1.end(), Myprint02());
	if (it==v1.end())
	{
		cout << "没有找到!" << endl;
	}
	else
	{
		cout << endl;
		cout << *it << endl;
	}
	//如果对一元谓词取反,用not1
	//如果对二元谓词取反,用not2
}

ptr_fun函数对象适配器:

void myprint(int val,int val2)
{
	cout << "val:" << val <<" "<< "val2:" << val2 << endl;
	cout << val + val2 << endl;
}


void main03()//ptr_fun把普通函数,转换成函数对象
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(rand() % 100);
	}
	for_each(v1.begin(), v1.end(),bind2nd(ptr_fun(myprint),10));
}

成员函数适配器 mem_fun、mem_fun_ref:

void main04()
{
	//如果容器中存放对象或指针,我们要打印的时候
	vector<My>v1;
	My p(10, 10), p1(20, 20), p2(30, 30), p3(40, 40);
	v1.push_back(p);
	v1.push_back(p1);
	v1.push_back(p2);
	v1.push_back(p3);
	//格式:&类名::函数名
	for_each(v1.begin(), v1.end(), mem_fun_ref(&My::show));
	cout << endl;
	vector<My*>v2;
	v2.push_back(&p);
	v2.push_back(&p1);
	v2.push_back(&p2);
	v2.push_back(&p3);
	for_each(v2.begin(), v2.end(), mem_fun(&My::show));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值