#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
//绑定函数 的参数列表是指,参数列表+返回值
struct PrintInfo2 :public binary_function<int,int,void> {
//编译报错 具有类型“const _Fn”的表达式会丢失一些 const-volatile 限定符以调用“void PrintInfo2::operator ()(int,int)”
//加上const
void operator()(int value,int delt) const {
cout << value +delt<< " ";
}
};
void testBindFunction() {
vector<int> v;
for (size_t i = 5; i < 16; i++) {
v.push_back(i);
}
int delt = 100;
for_each(v.begin(), v.end(), bind1st(PrintInfo2(), delt));
}
二、ptr_fun()
该函数主要是讲函数指针或者 函数转为可调用函数对象,然后再bind1st(object) 来绑定函数对象
void handleData(int inparams,int weParams) {
cout << " souce :" << inparams << " setParams:" << weParams << endl;
}
//绑定函数适配器
void testBindPtr() {
vector<int> v;
for (size_t i = 3; i < 11; i++) {
v.push_back(i);
}
//绑定 ptr_fun(handleData) 是将函数指针 变成函数对象,然后再调用bind 适配器
for_each(v.begin(),v.end(),bind2nd(ptr_fun(handleData),20));
}
三、mem_fun_ref()和mem_fun()区别
mem_fun_ref 绑定的类型是引用类型,mem_fun 是指针类型
class Person {
public:
Person(int age, string name) : age(age), name(name) {}
void showInfo() {
cout << "age: " << this->age << " name: " << this->name.c_str() << endl;
}
public:
int age;
string name;
};
void testBindField() {
Person p1(17,"abc");
Person p2(14,"efg");
vector<Person> v1;
v1.push_back(p1);
v1.push_back(p2);
for_each(v1.begin(),v1.end(),mem_fun_ref(&Person::showInfo));
cout << "--------------------------" << endl;
vector<Person*> v2;
v2.push_back(&p1);
v2.push_back(&p2);
for_each(v2.begin(), v2.end(), mem_fun(&Person::showInfo));
}