目录
bind1st、bind2nd使用:
bind1st:将operator()的第一个形参变量绑定成一个确定的值
bind2nd:将operator()的第二个形参变量绑定成一个确定的值vector<int> vec; srand(time(nullptr)); for (int i = 0; i < 20; ++i) { vec.push_back(rand() % 100 + 1); } showContainer(vec);
生成一个有20个随机数的vector容器。
template<typename Container> void showContainer(Container& con) { typename Container::iterator it = con.begin(); for (; it != con.end(); ++it) { cout << *it << " "; } cout << endl; }
自定义一个打印方式将数组依次打印
sort(vec.begin(), vec.end());//默认小到大排序 showContainer(vec);
从小到大给他排序然后打印出来;
//greater 二元函数对象 sort(vec.begin(), vec.end(), greater<int>());//大到小排序 showContainer(vec);
使用greater二元函数对象将其按照从大到小打印出来
这里如果想要将一个数据70按照顺序插入进去该如何做呢?
使用find_if函数找到第一个小于70的数据位置,返回位置并将70插入到该位置之前
但是find_if函数只能接收一元函数无法使用greater和less这个样的函数
==》绑定器 + 二元函数对象 =》 一元函数对象
find_if 原理:函数模板
template<typename Iterator, typename Compare> Iterator my_find_if(Iterator first, Iterator last, Compare comp) //遍历这2个迭代器之间的元素,如果满足函数对象的运算,就返回当前迭代器,如果都不满足,返回end() { for (; first != last; ++first) { if (comp(*first))//comp.operator()(*first)一元函数对象,因为要从容器拿1个元素和它指定的元素比较 //my_find_if需要1元函数对象,而在库里面都是二元的 { return first; } } return last; }
find_if的第二个模板参数要求为一元函数对象
bind1st、bind2nd原理:
//mybind1st(greater<int>(), 70) template<typename Compare, typename T> _mybind1st<Compare, T> mybind1st(Compare comp, const T& val) { //直接使用函数模板,好处是,可以进行类型的推演 return _mybind1st<Compare, T>(comp, val); }
这里使用一个函数模板,在其中调用_mybind1st函数对象完成目标的实现
template<typename Compare, typename T> class _mybind1st//绑定器是函数对象的一个应用 { public: _mybind1st(Compare comp, T val) :_comp(comp), _val(val) {} bool operator()(const T& second) { return _comp(_val, second);//greater 底层做事情的还是我们的二元函数对象 } private: Compare _comp; T _val; };