Keep Calm and Carry On

STL仿函数Functor

1. 仿函数

functor(仿函数)是早期的叫法,新的名称是 function objects(函数对象),意味具有函数功能的对象。从STL算法就可以看到,很多算法都具有两个版本,一个以 operator< 比较元素,另一个则是依靠用户传递的 functor 来比较元素。比如在排序中,根据传递的 functor,务必使得每两个相邻的元素都能让这个操作结果为true。

  1. unary_function
    unary_function 用来表示一元函数的参数类型和返回值类型:
1
2
3
4
5
6
7
8
template<typename _Arg, typename _Result>
struct unary_function {
/// @c argument_type is the type of the argument
typedef _Arg argument_type;

/// @c result_type is the return type
typedef _Result result_type;
};
  1. binary_function
    bianry_function 用来表示二元函数的参数类型和返回值类型:
1
2
3
4
5
6
7
8
9
10
11
template<typename _Arg1, typename _Arg2, typename _Result>
struct binary_function {
/// @c first_argument_type is the type of the first argument
typedef _Arg1 first_argument_type;

/// @c second_argument_type is the type of the second argument
typedef _Arg2 second_argument_type;

/// @c result_type is the return type
typedef _Result result_type;
};

2. STL内置的仿函数

1. 算术类型仿函数

除了取模和取反,其他都是二元运算

  • 加法: plus
  • 减法: minus
  • 乘法: multiplies
  • 除法: divides
  • 取模: modulus
  • 取反: negate

2. 关系运算类型仿函数

全都是二元运算

  • 等于: equal_to
  • 不等于: not_equal_to
  • 大于: greater
  • 大于等于: greater_equal
  • 小于: less
  • 小于等于: less_equal

3. 逻辑运算类型仿函数

and 和 or 是二元运算,not为一元运算

  • 逻辑运算 And: logical_and
  • 逻辑运算 Or: logical_or
  • 逻辑运算 Not: logical_or