设计模式定义
将一个class接口转换为另一个class接口
种类
容器adapter:stack, queue
迭代器adapter:reverse iterator, inserter iterator, iostream iterator
仿函数adapter
函数适配器
bind
bind1st/bind2nd:绑定第1/2个参数
template <class Operation>
class binder2nd : public unary_function<...> {
protected:
Operator op; //绑定的函数对象
typename Operation::second_argument_type value; //第二个参数值
public:
binder2nd(const Operation &x, const typename Operation::second_argument_type& y)
: op(x), value(y) {} //记录绑定的函数以及第二个参数值
typename Operation::result_type
operator()(const typename Operation::first_argument_type& x) const {
return op(x, value); //将value绑定为第二个参数
}
}
1.绑定函数/仿函数
auto new_function = bind(old_function, 1, _2);
//new_function(n) 相当于调用old_function(1,n)
2.绑定成员函数,_1为某个对象地址
Myclass object;
auto new_function = bind(&Myclass::old_function, _1);
// new_function(object) 相当于 object.old_function
3.绑定成员,_1为某个对象地址
auto new_member = bind(&Myclass::b, _1);
// new_member(object) 相当于object.b
not
not1/not2对应1/2个参数的函数
取否
compose
compose1:将unary function f(), g()结合为f(g(x))
compose2:将binary function f 与 unary function g1, g2 结合为f(g1(x), g2(x))
ptf-fun
将普通函数当作仿函数使用
pointer_to_unary_function
template <class Arg, class Result>
inline pointer_to_unary_function<Arg, Result>
ptr_fun(Result (*x)(Arg))
pointer_to_binary_function
template <class Arg, class Result>
inline pointer_to_binary_function<Arg1, Arg2, Result>
ptr_fun(Result (*x)(Arg1, Arg2))
mem_func/mem_fun_ref
将成员函数当作仿函数使用,实现泛型和多态的接轨
template <class S, class T>
inline mem_fun_t<S, T> mem_fun(S (T::*f)());
template <class S, class T>
inline const_mem_fun_t<S, T> mem_fun(S (T::*f)() const);
template <class S, class T, class A>
inline mem_fun1_t<S, T> mem_fun(S (T::*f)(A));
迭代器适配器
#include <iterator>
reverse_iterator
++变为--,--变为++
// 定义方式:
reverse_iterator<deque<int>::iterator>(id.end());
deque<int>::reverse_iterator(id.end());
copy(id.rbegin(), id.rend(), outite); //逆向拷贝
inserter iterators
将赋值操作变为insert/push_front/push_back操作
copy(ia+1, ia+2, front_inserter(id));
copy(ia, ia+1, inserter(id, ite));
IOStream Iterator
将迭代器绑定到iostream对象
ostream_iterator
operator=变为<<(如果有分隔符再输出分隔符)
++操作不作处理
ostream_iterator(ostream& s) : stream(&s), string(0) {}
ostream_iterator(ostream& s, const char *c) : stream(&s), string(c) {}
ostream_iterator<int> outite(cout, ' '); //输出至cout,用' ' 作为间隔符
copy(id.begin(), id.end(), outite);
istream_iterator
operator++操作变为>>
istream_iterator() : stream(&cin), end_marker(false) {}
istream_iterator(istream& s) : stream(&s) {read(); } //一创建就会引发read
istream_iterator<int> eos;
istream_iterator<int> initer(cin);
copy(inite, eos, inserter(id, id.begin()));