拓展C++ STL功能,函数适配器,复合函数composite

复合函数

数学定义:u=f(x,y),v=g(u),则把u=g(f(x,y)),称作g和f的复合函数,记作g。f,在STL中已经有很多的系统函数对象,如果将他们复合,将会实现更强大的功能,可惜STL的函数适配器没有提供这样的功能函数。于是,我仿造bind2nd和binder2nd的实现方法,自己写了composite和compositer的复合函数,实现g(f(x,y)的功能

函数原型:

// 可以参看C++ STL bind2nd的实现代码
//compositer对应binder2nd
//composite对应bind2nd
template<class Proc1, class Proc2>
class compositer :public binary_function
	<typename Proc1::first_argument_type,
	typename Proc1::second_argument_type,
	typename Proc2::result_type>
	template<class Proc1, class Proc2>
compositer<Proc1, Proc2> composite(const Proc1& op1, const Proc2& op2)

调用方法:

composite(op1,op2)(x,y),或者
compoister<op1_class,op2_class> cp=composite(op1,op2)
cp(x,y)

参数:

op1,内层复合函数,实现op1(x,y)
op2,外层复合函数,实现op2(op1(x,y))

返回值:

compositer,返回函数对象,调用compositer(x,y)实现op2(op1(x,y))

程序示例:

/*******************************************************************
* Copyright (C) Ashin Gau
*
* File Name   : composite.cpp
* Author      : Ashin Gau
* Create Time : 2015-10-9 09:07:26
* Mail        : helloxiyue@foxmail.com
* Blog        : http://blog.csdn.net/helloxiyue
*
* Description :  拓展C++ STL算法,添加复合函数,完成g(f(x,y))的数学定义
*                函数适配器 : 复合函数
*
******************************************************************/

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;

//可以参看C++ STL bind2nd的实现代码
//compositer对应binder2nd
//composite对应bind2nd
template<class Proc1,class Proc2>
class compositer:public binary_function
	<typename Proc1::first_argument_type,
	typename Proc1::second_argument_type,
	typename Proc2::result_type>
{
protected:
	Proc1 op1; //op1(x,y),内层函数
	Proc2 op2; //op2(op(x,y)),外层函数
public:
	compositer(const Proc1& p1,const Proc2& p2):op1(p1),op2(p2){}
	typename Proc2::result_type
		operator()(const typename Proc1::first_argument_type& x,
		const typename Proc1::second_argument_type& y) const{
		return op2(op1(x, y));
	}
};

template<class Proc1, class Proc2>
compositer<Proc1, Proc2> composite(const Proc1& op1, const Proc2& op2){
	return compositer<Proc1, Proc2>(op1, op2);
}

int main(){ 
	//输出结果:10-5+3=8
	cout << composite(minus<int>(),
			bind1st(plus<int>(), 3))(10,5) << endl;
	//三重复合
	//输出结果:(2.5*4.0/8.0) - 0.05 = 1.2
	cout << composite(composite(multiplies<double>(), 
			bind2nd(divides<double>(), 8.0)),
			bind2nd(minus<double>(),0.05)
			)(2.5, 4.0) << endl;
	//和C++ STL其它算法结合使用
	vector<int> v1, v2;
	for (int i = 1; i <= 7; i++){
		v1.push_back(i);
		v2.push_back(i + 2);
	}
	bool isEqual = equal(v1.begin(), v1.end(), v2.begin(), 
		//v1.element-v2.element == -2
		composite(minus<int>(), bind1st(equal_to<int>(),-2))
	);
	if (isEqual)
		cout << "v1 - v2 == -2" << endl;
	system("PAUSE");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值