🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # 简介 函数适配器bind1st bind2nd 现在我有这个需求 在遍历容器的时候,我希望将容器中的值全部加上100之后显示出来,怎么做? # bind1st和bind2nd ~~~ #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; #include <string> #include<vector> #include <set> //multset也是这个头文件 #include <map> #include<functional> #include<algorithm> //第一步:继承binary_function<参数1,参数2,返回类型> struct Myfunc :public binary_function<int, int, void> { void operator()(int v1, int v2)const //第二步:加上const成为常函数,参数变2个 { cout << "v1=" << v1 << endl; cout << "v2=" << v2 << endl; //cout << v1 << " " << endl; cout << v1 + v2 << endl;//第三步:实现函数体 } }; //需求:打印时,每个元素加100然后打印出来 void test() { vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); v.push_back(50); //for_each(v.begin(), v.end(), Myfunc()); //第四步:用bind2nd来绑定函数对象 //2.bind1st和bind2nd的区别 //bind1st把100绑定给第一个参数 //bind2nd把100绑定给第二个参数 for_each(v.begin(), v.end(), bind2nd(Myfunc(), 100)); } ~~~ # not1和not2取反 1. not1和not2区别: not针对一元函数对象,not2针对二元函数对象 2. 使用not1和not2 ~~~ struct MyNotfunc { bool operator() (int v) { return v >= 20; } }; void test() { vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); v.push_back(50); vector<int>::iterator it = find_if(v.begin(), v.end(), MyNotfunc()); if (it == v.end()) { cout << "查找失败" << endl; } else { cout << "查找成功: " << *it << endl; } } ~~~ **适配** ~~~ //第一步继承 struct MyNotfunc : public unary_function<int, bool> { //第二步:变为常函数 bool operator() (int v) const { return v >= 20; } }; void test() { vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); v.push_back(50); //第三步适配 vector<int>::iterator it = find_if(v.begin(), v.end(), not1(MyNotfunc())); if (it == v.end()) { cout << "查找失败" << endl; } else { cout << "查找成功: " << *it << endl; } } ~~~ # 普通函数适配 普通函数进行适配: `ptr_fun` ~~~ void myprint2(int val, int val2) { cout << val + val2 << " "; } void test03() { vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); v.push_back(50); //第二步:把普通函数变为函数对象 ptr_fun for_each(v.begin(), v.end(), bind2nd(ptr_fun(myprint2),100)); } ~~~ # 成员函数适配 1. `mem_fun`: 如果存储的是对象指针,需要使用`mem_fun` 2. `mem_fun_ref`:如果存储的是对象,需要使用`mem_fun_ref` ~~~ class Maker { public: string name; int age; public: Maker(string name, int age) { this->name = name; this->age = age; } //成员函数 void MyprintMaker() { cout << "Name: " << this->name << " Age: " << this->age << endl; } }; void test03() { vector<Maker> v; v.push_back(Maker("aaa", 10)); v.push_back(Maker("bbb", 20)); v.push_back(Maker("ccc", 30)); //当容器存储的是对象,用mem_fun_ref适配他的成员函数 for_each(v.begin(), v.end(), mem_fun_ref(&Maker::MyprintMaker)); cout << "-------------" << endl; vector<Maker*> vp; vp.push_back(new Maker("aaa", 10)); vp.push_back(new Maker("bbb", 20)); vp.push_back(new Maker("ccc", 30)); //当容器存储的是对象指针,用mem_fun适配他的成员函数 for_each(vp.begin(), vp.end(), mem_fun(&Maker::MyprintMaker)); } ~~~