C++ STL: functor

0 前言

最近上C++选修,又看了看STL源码,就整理一下吧。

1 总体印象

accumulate() 相加->其他操作

sort() 重载operator<

将某种操作当成算法的参数

  • 将该操作设计成一个函数,再将这个函数指着当成算法的一个参数(存在问题:函数指针不能满足STL抽象性要求)

  • 将该操作设计成一个仿函数(class),再将该functor产生一个对象,将这个对象作为算法的一个参数

functor class need to overload operator().

greater<int> ig;

ig(4, 6);

greater<int>()(4, 6);//无名对象

分类:一元/二元 算术Arithmetic/关系/逻辑

#include<functional>

2 Apaptable

function adapter

they need to have their own associative types, like five kinds of iterator.

don’t worry about speed, they are complied before running.

2.1 unary_function

all the unary_function need to inherit code as follows:

```
template<class Arg, class Result>
struct unary_function
{
    typedef Arg argument_type;
    typedef Result result_type;
};

template<class T>
struct negate : public unary_function<T, T>
{
    T operator()(const T& x) const
    {
        return -x;
    }
}
```

2.2 binary_function

```
template<class Arg, class Arg2, class Result>
struct binary_function
{
    typedef Arg first_argument_type;
    typedef Arg second_argument_type;
    typedef Result result_type;
};
template<class T>
struct plus : public binary_function<T, T, T>
{
    T operator()(const T& x, const T& y) const
    {
        return x + y;
    }
}
```

3 Arithmetic Functor

plus / minus / mutillies / divides / modelus / negate

plus<int> plusobj;

int c = plusobj()(2, 3);

//c = 5;

STL仿函数的主要功能是搭配STL算法使用

accumulate(v.begin(), v.end(), plus<int>());

4 Relational functor

大于/小于/大于等于/小于等于/不等于/等于

```C++
template<class Arg, class Arg2, class Result>
struct binary_function
{
    typedef Arg first_argument_type;
    typedef Arg second_argument_type;
    typedef Result result_type;
};
template<class T>
struct equality : public binary_function<T, T, bool>
{
    bool operator()(const T& x, const T& y) const
    {
        return x == y;
    }
}
```

sort(v.begin(), v.end(), greater<int>());

5 Logical Functor

And / Or / Not

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值