绑定器
C++11从Boost库中引入了bind绑定器和function函数对象机制
绑定器+二元函数对象 = 一元函数对象
bind1st 绑定第一个
bind2nd 绑定第二个
#include <iostream>
#include <memory>
#include <vector>
#include <functional>
#include <ctime>
#include <algorithm>
using namespace std;
template<typename Container>
void show(Container& con)
{typename Container::iterator it = con.begin();for (; it != con.end(); ++it){cout << *it << " ";}cout << endl;
}
int main()
{vector<int> vec;srand(time(nullptr));for (int i = 0; i < 20;++i){vec.push_back(rand()%100+1);}show(vec);sort(vec.begin(), vec.end());show(vec);sort(vec.begin(), vec.end(),greater<int>());show(vec);vector<int>::iterator it = find_if(vec.begin(), vec.end(), bind1st(greater<int>(), 70));if (it != vec.end()){vec.insert(it, 70);}show(vec);return 0;
}
C++11从Boost库中引入了bind绑定器和function函数对象机制
function函数对象包含#include <functional>
function:绑定器,函数对象,lambda表达式,它们只能使用在一条语句中
从function的类模板定义处,看到希望用一个函数类型实例化function
#include <iostream>
#include <memory>
#include <vector>
#include <functional>
#include <ctime>
#include <algorithm>
#include <string>
using namespace std;
void hello1()
{cout << "hello world" << endl;
}
void hello2(string str)
{cout << str << endl;
}
int main()
{function<void()> fun1(hello1);fun1();//调用的小括号运算符重载function<void(string)> fun2(hello2);fun2("hello world2");return 0;
}
1.用函数类型实例化function
2.通过function调用operator()函数的时候,需要根据函数类型传入相应的参数
模板的特例化,有完全特例化优先匹配完全特例化,没有完全特例化再匹配部分特例化
lambda
C++11函数对象的升级版 =》lambda表达式
函数对象的缺点:
函数对象使用在泛型算法参数传递,比较性质/自定义操作 优先级队列 智能指针
lambda表达式的语法:
[捕获外部变量](形参列表)->返回值{操作代码};
#include <iostream>
#include <memory>
#include <vector>
#include <functional>
#include <ctime>
#include <algorithm>
#include <string>
using namespace std;
int main()
{auto fun = [](int a, int b)->int {return a + b; };cout << fun(20, 30) << endl;return 0;
}
如果lambda表达式的返回值不需要,那么“->返回值”可以省略
[]表示不捕获任何外部变量
[=]以传值的方式捕获外部的所有变量
[&]以传引用的方式捕获外部的所有变量
[this]捕获外部的this指针
[=,&a]以传值的方式捕获外部的所有变量,但是a变量以传引用的方式捕获
[a,b]以值传递的方式捕获外部变量a,b
[a,&b]a以值传递捕获,b以传引用的方式捕获
既然lambda表达式只能使用在语句当中,如果想跨语句使用之前定义好的lambda表达式,怎么办?用什么类型来表示lambda表达式?
解决方法:用函数对象function表示lambda的类型,lambda->函数对象