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