头文件:
#include
先上实例:
#include
#include
using namespace std; using namespace std::placeholders; int main() { auto fun = [](int *array, int n, int num){ for (int i = 0; i < n; i++) { if (array[i] > num) cout << array[i] << ends; } cout << endl; }; int array[] = { 1, 3, 5, 7, 9 }; //_1,_2 是占位符 auto fun1 = bind(fun, _1, _2, 5); //等价于调用fun(array, sizeof(array) / sizeof(*array), 5); fun1(array, sizeof(array) / sizeof(*array)); cin.get(); return 0; }
运行结果:
7 9
auto newfun = bind(fun, arg_list);
其中fun是一函数,arg_list是用逗号隔开的参数列表。调用newfun(),newfun会调用fun(arg_list);
2._1,_2是占位符,定义于命名空间placeholders中。_1是newfun的第一个参数,_2是newfun的第二个参数,以此类推。
int fun(int a, int b); auto newfun = bind(fun, _2, _1);
调用newfun(1, 2);相当于调用fun(2, 1);
1.bind函数的基本介绍
bind函数的最根本的作用就是可以把一个参数较多的函数给封装成参数较少的函数,因此对于上述find_if函数的问题,我们可以自定义一个含俩个参数的函数,然后通过bind函数进行封装,使之变成含一个参数的新函数(新函数会调用原来的函数),这样新函数就可以被find_if函数的第三个参数所使用了
2.bind的基本形式与使用
bind函数定义在头文件functional中,我们可以将bind函数看作一个通用的函数适配器,它的一般形式如下
auto newFun = bind(oldFun,arg_list);
#include
#include
#include
#include
using namespace std; bool check_size(const int x,int sz) { return x > sz; } int main(void) { vector<int> v = { 1,2,3,4,5,6,7,8,9 }; int n = 5; //有bind函数新封装生成的函数,其内部调用了check_size auto new_check_size = bind(check_size,std::placeholders::_1,n); auto it = find_if(v.begin(),v.end(),new_check_size); cout<<"第一个大于n的数为:"<<*it<
return
0; }
3.用bind重排源函数的参数顺序
用bind重排源函数的参数顺序只需将新函数与源函数的参数列表进行跌倒即可
实现代码如下
//假定源函数如下
bool oldFun(int a1,int a2);
//使用bind封装源函数如下
auto newFun = bind(old_Fun,_2,_1);
4.使用ref给源函数传递引用参数
#include
#include
#include
#include
using namespace std; bool check_size(const int x,int &sz) { //改变sz的值 sz = 6; return x > sz; } int main(void) { vector<int> v = { 1,2,3,4,5,6,7,8,9 }; int n = 5; //传递n的引用 auto new_check_size = bind(check_size,std::placeholders::_1,ref(n)); auto it = find_if(v.begin(),v.end(),new_check_size); cout<<"n的值为为:"<
return
0; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/199637.html原文链接:https://javaforall.net
