STL 笔记2
仿函数:STL中所有的仿函数都unary_function和binary_function派生,其定义如下:
template
<class_Arg, class
_Result>
structunary_function
{
typedef _Arg argument_type;
typedef _Result result_type;
};
template
<class_Arg1, class _Arg2, class
_Result>
structbinary_function
{
typedef _Arg1 first_argument_type;
typedef _Arg2 second_argument_type;
typedef _Result result_type;
};
STL仿函数最多支持两个函数参数,在其中分别定义了first_argument_type,second_argument_type,
result_type;分别定义参数和返回值。
template
<class_Tp>
structgreater_equal :
public
binary_function<_Tp,_Tp,bool>
{
bool operator()(const _Tp& __x,
const_Tp& __y) const
{
return __x >= __y;
}
};
template
<class_Tp>
struct
less_equal: public
binary_function<_Tp,_Tp,bool>
{
bool operator()(const _Tp& __x,
const_Tp& __y) const
{
return __x <= __y;
}
};
template
<class_Tp>
struct
logical_and: public
binary_function<_Tp,_Tp,bool>
{
bool operator()(const _Tp& __x,
const_Tp& __y) const
{
return __x && __y;
}
};
template
<class_Tp>
struct
logical_or: public
binary_function<_Tp,_Tp,bool>
{
bool operator()(const _Tp& __x,
const_Tp& __y) const
{
return __x || __y;
}
};
template
<class_Tp>
struct
logical_not: public
unary_function<_Tp,bool>
{
bool operator()(const _Tp& __x) const
{
return !__x;
}
};
template
<class_Predicate>
class
unary_negate
: public
unary_function<typename_Predicate::argument_type,
bool>
{
protected:
_Predicate _M_pred;
public:
explicit unary_negate(const _Predicate&__x) :
_M_pred(__x)
{}
bool operator()(const
typename_Predicate::argument_type& __x) const
{
return !_M_pred(__x);
}
};
template
<class_Predicate>
inlineunary_negate<_Predicate>
not1(const_Predicate&
__pred)
{
returnunary_negate<_Predicate>(__pred);
}
template
<class_Predicate>
classbinary_negate
: publicbinary_function<typename
_Predicate::first_argument_type,
typename_Predicate::second_argument_type,
bool>
{
protected:
_Predicate _M_pred;
public:
explicit binary_negate(const_Predicate& __x) :
_M_pred(__x)
{}
bool operator()(const
typename_Predicate::first_argument_type& __x,
const typename_Predicate::second_argument_type&
__y) const
{
return !_M_pred(__x, __y);
}
};
template
<class_Predicate>
inlinebinary_negate<_Predicate>
not2(const_Predicate&
__pred)
{
returnbinary_negate<_Predicate>(__pred);
} 仿函数调用时一般通过内联的函数模板调用,如not2.
|