utilities——C++常用仿函数

30 篇文章 2 订阅
#include <functional>
  • unary_function

    // STL 规定,每一个Adaptable(可配接的) Unary Function 都应该继承此类别
    template <class Arg, class Result>
    struct unary_function
    {
        typedef Arg argument_type;
        typedef Result result_type;
    }
  • binary_function

    // STL 规定,每一个 Adaptable Binary Function 都应该继承此类别
    template<class Arg1, class Arg2, class Result>
    struct binary_function
    {
        typedef Arg1 first_argument_type;
        typedef Arg2 second_argument_type;
        typedef Result result_type;
    }

greater<>/less<>

// 大的在前,小的在后,也即在排序时,逆序输出
template<typename T>
struct greater :public binary_function<T, T, bool>
{
    result_type operator()(const first_result_type& left, const second_result_type& right) const
    {
        return left > right;
    }
}

如果我们要实现一个绝对值大的在前,绝对值小的在后,也即比较的是绝对值的大小。

template<typename T>
struct abs_greater :public binary_function<T, T, bool>
{
    bool operator()(const T& left, const T& right) const
    {
        return abs(left) > abs(right);
    }
}

排序准则(sorting criterion)

或许因为不想,或许因为不能,无法使用一般的 operator<对这些对象排序,而是必须以某种特定的规则(通常基于某些成员函数)来排序,此时便是 function objects 施展身手的舞台;

class Person
{
public:
    std::string firstname() const;
    std::string secondname() const;
    ...
}

class PersonSortCriterion
{
public:
    bool operator() (const Person& left, const Person& right) const
    {
        return left.lastname() < right.lastname() || 
            (left.lastname() == right.lastname() && left.firstname() < right.firstname());
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值