分享

STL 笔记2

 quasiceo 2012-11-12

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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多