函数适配器 bind2nd 和 bind1st 两者差别在于内部参数调用顺序不同。我们完全可以自己写一个函数适配器。为了泛化,可以做成模板。
#include "stdafx.h"
#include "stdio.h"
#include "vector"
#include "algorithm"
#include "functional"
using std::vector;
class MyBind{
public:
void operator ()(int &left, int right)
{
left += right;
}
};
class MyBind2nd{
public:
MyBind2nd(MyBind func, int val) :op(func), value(val){}
void operator()(int &number){
op(number, value);
}
private:
MyBind op;
int value;
};
int main(int argc, char **argv, char ** env)
{
vector<int> vecInt = { 2, 2, 0, 2, 1, 2, 3, 2, 4, 2, 2 };
for_each(vecInt.begin(), vecInt.end(), [](int n){fprintf(stdout, "%d\t", n); });
fprintf(stdout, "\n");
for_each(vecInt.begin(), vecInt.end(), MyBind2nd(MyBind(), 10));
for_each(vecInt.begin(), vecInt.end(), [](int n){fprintf(stdout, "%d\t", n); });
system("pause");
}