为使类属性算法具有灵活性,STL常用函数重载机制为算法提供两种形式,算法的第一种形式使用的是常规操作来实现目标。在第二种形式中,算法可以根据用户指定的准则对元素进行处理。这种准则是通过函数对象来传递的。函数对象世纪上是重载了operator()的类模版。
STL提供了许多函数对象,这些对象包含在头文件<functional>中。
函数对象 | 说明 |
1、算术函数对象: | |
plus<T> | x+y |
minus<T> | x-y |
multiplies<T> | x*y |
divides<T> | x/y |
modulus<T> | x%y |
negate<T> | -x |
2、关系(比较)函数对象: | |
equal_to<T> | x==y |
not_equal_to<T> | x!=y |
greater<T> | x>y |
greater_equal<T> | x>=y |
less<T> | x<y |
less_equal<T> | x<=y |
3、逻辑函数对象: | |
logical_not<T> | !x |
logical_and<T> | x&&y |
logical_or<T> | x||y |
STL中包含许多预定义的函数对象,其中有:
- 算术操作:plus, minus, multiplies, divides, modulus, 和 negate,例:
assert(V2.size() >= V1.size() && V3.size() >= V1.size());
transform(V1.begin(), V1.end(), V2.begin(), V3.begin(),modulus<int>());把V1[i]%V2[i]存入V3[i]。
- 比较操作:equal_to, not_equal_to, greater, less, greater_equal, 和 less_equal,例:
list<int>::iterator first_nonnegative = find_if(L.begin(), L.end(), bind2nd(greater_equal<int>(), 0));
在L中找到第一个大于等于0的元素。
- 逻辑操作:logical_and, logical_or, 和 logical_not,例:
char str[MAXLEN];
const char* wptr = find_if(str, str + MAXLEN,compose2(logical_or<bool>(),bind2nd(equal_to<char>(), ' '),bind2nd(equal_to<char>(), '\n')));在str中找到第一个空格或行尾。
以上三类都是模板类,要生成一个函数对象需要实例化。同时在使用时,需要注意:
- 算法需要的参数是什么类型的函数对象,是一元函数还是二元函数。
- 输入容器内元素类型是否与函数对象参数兼容,输出容器内元素是否与函数对象返回值兼容。
- 修改、组装已有函数对象生成新的函数对象:unary_compose, binary_compose, unary_negate, binary_negate, binder1st, binder2nd, pointer_to_unary_function, pointer_to_binary_function, mem_fun_t, mem_fun_ref_t, mem_fun1_t 和mem_fun1_ref_t。这类函数对象就是所谓的函数对象适配器,由于书写生涩,一般不会直接实例化,都有对应的辅助函数(一般都是内联型)简化调用。
函数对象模板类名 | 辅助函数名 | 说明 |
unary_compose | compose1 | unary_compose(const AdaptableUnaryFunction1& f, const AdaptableUnaryFunction2& g); 生成一个一元函数对象,操作为“f(g(x))”;vc6/7自带stl没有定义。 |
binary_compose | compose2 | binary_compose(const AdaptableBinaryFunction& f, const AdaptableUnaryFunction1& g1, const AdaptableUnaryFunction1& g2); 生成一个二元函数对象,操作为“f(g1(x), g2(x))”;vc6/7自带stl没有定义。 |
unary_negate | not1 | unary_negate(const AdaptablePredicate& pred); 一元谓词取非。 |
binary_negate | not2 | binary_negate(const AdaptableBinaryPredicate& pred); 二元谓词取非。 |
binder1st | bind1st | binder1st(const AdaptableBinaryFunction& F, AdaptableBinaryFunction::first_argument_type c); 把二元函数对象的第一个参数绑定为c,生成一个一元函数对象。 |
binder2nd | bind2nd | binder2nd(const AdaptableBinaryFunction& F, AdaptableBinaryFunction::second_argument_type c); 把二元函数对象的第二个参数绑定为c,生成一个一元函数对象。 |
pointer_to_unary_function | ptr_fun | 把普通全局函数或全局函数指针(只能有1个或2个参数)转换成函数对象。 ptr_fun有两个原型分别生成pointer_to_unary_function对象和pointer_to_binary_function对象。 |
pointer_to_binary_function | ||
mem_fun_t | mem_fun | 把某个类的成员函数(只能有0个或1个参数,因为类成员函数的第一个参数已定义为this指针)转换成函数对象。 mem_fun有两个原型分别生成mem_fun_t对象(是个一元函数对象)和mem_fun1_t对象(是个二元函数对象)。 |
mem_fun1_t | ||
mem_fun_ref_t | mem_fun_ref | 类似mem_fun,区别如下: struct T{ list<T*> lstT; list<T> lstT; |
mem_fun1_ref_t | ||