1.仿函数简介
顾名思义,就是类似函数,实际上是个类,那为何叫仿函数,因为它用起来形式像个函数一样,实际上是由于重载了operator(),所以仿函数也叫做函数对象;
最基本的函数对象包括:
1.1 generator
A Generator is a kind of function object: an object that is called as if it were an ordinary C++ function. A Generator is called with no arguments.
1.2 unary function
A Unary Function is a kind of function object: an object that is called as if it were an ordinary C++ function. A Unary Function is called with a single argument.
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
Note: This class has been deprecated in C++11.
比如less的实现,在C++98是
template <class T> struct less : binary_function <T,T,bool> {
bool operator() (const T& x, const T& y) const {return x<y;}
};
在C++11是
template <class T> struct less {
bool operator() (const T& x, const T& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
1.3 binary function
A Binary Function is a kind of function object: an object that is called as if it were an ordinary C++ function. A Binary Function is called with two arguments.
template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
Note: This class has been deprecated in C++11.
2. 常见的预定义仿函数:
2.1算术类
除了否定为一元,其他都为二元仿函数。
减法:minus<T>
乘法:multiplies<T>
除法:divides<T>
求余:modulus<T>
否定:negate<T>
2.2关系运算类
都是二元仿函数。
等于:equal_to<T>
不等于:not_equal_to<T>
大于:greater<T>
大于等于:greater_equal<T>
小于:less<T>
小于等于:less_equal<T>
2.3逻辑运算类
与和或为二元仿函数,否为一元仿函数。
与:logical_and<T>
或:logical_or<T>
否:logical_not<T>
3.仿函数配接器
3.1.1 bind1st
template <class Operation, class T>
binder1st<Operation> bind1st (const Operation& op, const T& x);
The function object returned by bind1st has its operator() defined such that it takes only one argument. This argument is used to call binary function object op with x as the fixed value for the first argument.
It is defined with the same behavior as:
| |
Parameters
-
op
- Binary function object derived from binary_function. x
- Fixed value for the first parameter of op.
Return value
An unary function object equivalent to op but with the first parameter always set to x.binder1st is a type derived from unary_function.
3.1.2 binder1st
template <class Operation> class binder1st;
binder1st is generally used as a type. The function bind1st (also defined in header <functional> ) can be used to directly construct an object of this type.
binder1st is constructed using a binary function object as argument. A copy of this object is used by its member operator() to generate a result from its parameter and the fixed value set on construction.
This class is derived from unary_function and is typically defined as:
| |
binder1st class is specifically designed to bind function objects ( operations ) derived from binary_function (it requires member first_argument_type and second_argument_type ).