温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++ STL bind1st bind2nd bind 的使用方法

发布时间:2021-07-19 10:48:23 来源:亿速云 阅读:116 作者:chen 栏目:互联网科技

本篇内容主要讲解“C++ STL bind1st bind2nd bind 的使用方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++ STL bind1st bind2nd bind 的使用方法”吧!

说明

bind1st() 和 bind2nd(),在 C++11 里已经 deprecated 了,建议使用新标准的 bind()
下面先说明bind1st() 和 bind2nd()的用法,然后在说明bind()的用法。

头文件

#include <functional>

作用

bind1st()bind2nd()都是把二元函数转化为一元函数,方法是绑定其中一个参数。
bind1st()是绑定第一个参数。
bind2nd()是绑定第二个参数。

例子

#include <iostream>#include <algorithm> #include <functional> using namespace std; int main() { int numbers[] = { 10,20,30,40,50,10 }; int cx; cx = count_if(numbers, numbers + 6, bind2nd(less<int>(), 40)); cout << "There are " << cx << " elements that are less than 40.\n"; cx = count_if(numbers, numbers + 6, bind1st(less<int>(), 40)); cout << "There are " << cx << " elements that are not less than 40.\n"; system("pause"); return 0; }
There are 4 elements that are less than 40.There are 1 elements that are not less than 40.

分析
less()是一个二元函数,less(a, b)表示判断a<b是否成立。

所以bind2nd(less<int>(), 40)相当于x<40是否成立,用于判定那些小于40的元素。

bind1st(less<int>(), 40)相当于40<x是否成立,用于判定那些大于40的元素。

bind()

bind1st() 和 bind2nd(),在 C++11 里已经 deprecated 了.bind()可以替代他们,且用法更灵活更方便。

上面的例子可以写成下面的形式:

#include <iostream>#include <algorithm> #include <functional> using namespace std; int main() { int numbers[] = { 10,20,30,40,50,10 }; int cx; cx = count_if(numbers, numbers + 6, bind(less<int>(), std::placeholders::_1, 40)); cout << "There are " << cx << " elements that are less than 40.\n"; cx = count_if(numbers, numbers + 6, bind(less<int>(), 40, std::placeholders::_1)); cout << "There are " << cx << " elements that are not less than 40.\n"; system("pause"); return 0; }

std::placeholders::_1 是占位符,标定这个是要传入的参数。
所以bind()不仅可以用于二元函数,还可以用于多元函数,可以绑定多元函数中的多个参数,不想绑定的参数使用占位符表示。
此用法更灵活,更直观,更便捷。

到此,相信大家对“C++ STL bind1st bind2nd bind 的使用方法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI