Руководство по стандартной библиотеке шаблонов STL

Привязки (Binders)


Привязки bind1st и bind2nd берут функциональный объект f двух параметров и значение x и возвращают функциональный объект одного параметра, созданный из f с первым или вторым параметром соответственно, связанным с х.

template <class Predicate> class binder1st : public unary_function { protected: Operation op; Operation::first_argument_type value; public: binder1st(const Operation& x, const Operation::first_argument_type& y) : op(x), value(y) {} result_type operator()(const argument_type& x) const { return op(value, x); } }; template <class Operation, class T> binder1st<0peration> bind1st(const Operation& op, const T& x) { return binder1st<0peration>(op, Operation::first_argument_type(x)); } template <class Operation> class binder2nd : public unary_function<0peration::first_argument_type, Operation::result_type> { protected: Operation op; Operation::second_argument_type value; public: binder2nd(const Operation& x, const Operation::second_argument_type& y) : op(x), value(y) {} result_type operator()(const argument_type& x) const { return op(x, value); } }; template <class Operation, class T> binder2nd<Operation> bind2nd(const Operation& op, const T& x) { return binder2nd<0peration>(op, Operation::second_argument_type(x)); }

     Например, find_if(v.begin(), v.end(), bind2nd(greater<int>(), 5)) находит первое целое число в векторе v большее, чем 5; find_if(v.begin(), v.end(), bind1st(greater<int>(), 5)) находит первое целое число в v меньшее, чем 5.



Содержание раздела