C++ STL函数绑定器

代码示例:

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;


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

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

	return 0;
}

运行结果:

C++ STL函数绑定器_第1张图片





你可能感兴趣的:(C++)