c++ bind函数

c++ bind函数头文件 includefunct 前言函数绑定 bind 函数用于把某种形式的参数列表与已知的函数进行绑定 形成新的函数 这种更改已有函数调用模式的做法 就叫函数绑定 需要指出 bind 就是函数适配器 先上实例 includeiostr includefunct usingnamespa

头文件:

#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

(0)
上一篇 2026年3月20日 下午12:33
下一篇 2026年3月20日 下午12:33


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号