代码示例:
#include <iostream> #include <map> #include <vector> #include <algorithm> #include <functional> #include <string> using namespace std; /* 1.函数接配器 bind1st bind2nd //bind1st 绑定左操作数 //bind2nd 绑定右操作数 not1 not2 //not1 给一元函数对象取反 //not2 给二元函数对象取反 */ /* 查找大于某个数的算法 */ /* 二元函数对象 */ template<class _Ty> class MyLess { // functor for operator< bool operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator< to operands return (_Left < _Right); } }; /* 一元函数对象 */ template<typename T> class CCompare { public: CCompare(T val) :data(val){} bool operator()(T rhs) { return data < rhs; } private: T data; }; template<typename Comp> class MyBinder2 { public: MyBinder2(Comp f, const typename Comp::second_argument_type& data) { fn = f; val = data; } bool operator()(const typename Comp::first_argument_type& first) { return fn(first, val); } private: Comp fn; typename Comp::second_argument_type val; }; template<typename _Fn2, typename T> MyBinder2<_Fn2> mybindsecond(_Fn2 fn, const T& value) { return MyBinder2<_Fn2>(fn, value); } template<typename Comp> class MyNote1 { public: MyNote1(Comp f) :fn(f){} bool operator()(const typename Comp::argument_type& val) { return !fn(val); } private: Comp fn; }; template<typename Fn2> MyNote1<Fn2> Not1(Fn2 fn) { return MyNote1<Fn2>(fn); } int main() { int arr[] = { 15, 23, 13, 13, 154, 887, 654, 6 }; int len = sizeof(arr) / sizeof(arr[0]); vector<int> vec(arr, arr + len); less<int>(); vector<int>::iterator it = find_if(vec.begin(), vec.end(), not1(bind2nd(less<int>(), 100))); if (it != vec.end()) { cout << *it << endl; } return 0; }
运行结果: