C++ STL函数绑定器

代码示例:

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


/*
1.函数接配器
bind1st  bind2nd
//bind1st  绑定左操作数
//bind2nd  绑定右操作数
not1 not2
//not1    给一元函数对象取反
//not2    给二元函数对象取反
*/
/*
查找大于某个数的算法
*/
/*
二元函数对象
*/
template<class _Ty>
class MyLess
{	// functor for operator<
	bool operator()(const _Ty& _Left, const _Ty& _Right) const
	{	// apply operator< to operands
		return (_Left < _Right);
	}
};
/*
一元函数对象
*/
template<typename T>
class CCompare
{
public:
	CCompare(T val) :data(val){}
	bool operator()(T rhs)
	{
		return data < rhs;
	}
private:
	T data;
};
template<typename Comp>
class MyBinder2
{
public:
	MyBinder2(Comp f,
		const typename Comp::second_argument_type& data)
	{
		fn = f;
		val = data;
	}
	bool operator()(const typename Comp::first_argument_type& first)
	{
		return fn(first, val);
	}
private:
	Comp fn;
	typename Comp::second_argument_type val;
};
template<typename _Fn2,
	typename T>
	MyBinder2<_Fn2> mybindsecond(_Fn2 fn, const T& value)
{
	return MyBinder2<_Fn2>(fn, value);
}

template<typename Comp>
class MyNote1
{
public:
	MyNote1(Comp f) :fn(f){}
	bool operator()(const typename Comp::argument_type& val)
	{
		return !fn(val);
	}
private:
	Comp fn;
};
template<typename Fn2>
MyNote1<Fn2> Not1(Fn2 fn)
{
	return MyNote1<Fn2>(fn);
}
int main()
{
	int arr[] = { 15, 23, 13, 13, 154, 887, 654, 6 };
	int len = sizeof(arr) / sizeof(arr[0]);
	vector<int> vec(arr, arr + len);
	less<int>();
	vector<int>::iterator it = find_if(vec.begin(),
		vec.end(), not1(bind2nd(less<int>(), 100)));
	if (it != vec.end())
	{
		cout << *it << endl;
	}

	return 0;
}

运行结果:






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值