STL分析(八 仿函数)

//算术类
template <class T>
struct plus : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const
        { return x + y; }
};
 
template <class T>
struct minus : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const
        { return x - y; }
};
 
 
//逻辑运算类
template <class T>
struct logical_and : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const
        { return x && y; }
};
 
 
//相对关系类
template <class T>
struct equal_to : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const
        { return x == y; }
};
 
template <class T>
struct less : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const
        { return x < y; }
};

可以看到所有标准库提供的functor都继承了binary_function,有的是unary_function,这些就是融入了STL的条件。
调用:

#include <iostream>     // std::cout
#include <functional>   // std::plus
#include <algorithm>    // std::transform
using namespace std;
int main(void)
{
    cout << minus<int>()(10,5) << endl;//5
    cout << multiplies<int>()(10,5) << endl;//50
    cout << divides<int>()(10,5) << endl;//2
    cout << modulus<int>()(10,5) << endl;//0
    cout << negate<int>()(10) << endl;//-10
    return 0;
}

在这里插入图片描述
继承后的unary_function和binary_function占0字节,不占用内存,但赋予了仿函数一对typedef,继承了这些函数的仿函数叫做“可适配的仿函数”。当仿函数需要被适配时,适配器会问仿函数一些问题,只有继承了这些typedef的仿函数可以回答这些问题。

GNU C++独有的functors

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值