一、适配器
三种类型的适配器:
容器适配器:用来扩展7种基本容器,利用基本容器扩展形成了栈、队列和优先级队列
迭代器适配器:(反向迭代器、插入迭代器、IO流迭代器)
函数适配器:函数适配器能够将仿函数和另一个仿函数(或某个值、或某个一般函数)结合起来。
针对成员函数的函数适配器
针对一般函数的函数适配器
二、函数适配器示例
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream>
#include <algorithm> #include <functional> #include <vector> using namespace std; bool is_odd( int n) { return n % 2 == 1; } int main( void) { int a[] = { 1, 2, 3, 4, 5}; vector< int> v(a, a + 5); cout << count_if(v.begin(), v.end(), is_odd) << endl; //计算奇数元素的个数 // 这里的bind2nd将二元函数对象modulus转换为一元函数对象。 //bind2nd(op, value) (param)相当于op(param, value) cout << count_if(v.begin(), v.end(), bind2nd(modulus< int>(), 2)) << endl; //bind1st(op, value)(param)相当于op(value, param); cout << count_if(v.begin(), v.end(), bind1st(less< int>(), 4)) << endl; return 0; } |
这里的bind2nd将二元函数对象modulus转换为一元函数对象。是如何做到的呢?跟踪源码就知道了。
首先,bind2nd 是一个模板函数,如下:
C++ Code
1
2 3 4 5 6 7 8 9 |
// TEMPLATE FUNCTION bind2nd template < class _Fn2, class _Ty > inline binder2nd<_Fn2> bind2nd( const _Fn2 &_Func, const _Ty &_Right) { // return a binder2nd functor adapter typename _Fn2::second_argument_type _Val(_Right); return (std::binder2nd<_Fn2>(_Func, _Val)); } |
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// TEMPLATE CLASS bi |