随笔 - 741  文章 - 0  评论 - 260  阅读 - 416万

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()不仅可以用于二元函数,还可以用于多元函数,可以绑定多元函数中的多个参数,不想绑定的参数使用占位符表示。
此用法更灵活,更直观,更便捷。

参考

http://www.cplusplus.com/reference/functional/bind1st/
http://www.cplusplus.com/reference/functional/bind2nd/
http://www.cplusplus.com/reference/functional/bind/



作者:book_02
链接:https://www.jianshu.com/p/f337f42822fe
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted on   莫水千流  阅读(1072)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2016-08-19 QT在线
2016-08-19 git常用命令
2016-08-19 git 服务器搭建,在自己服务器上搭建私有仓库
2016-08-19 窗体皮肤实现 - 增加Toolbar的交互性
2016-08-19 使用VisualStudio2015开发QT项目
2016-08-19 界面控件 - 滚动条ScrollBar
2016-08-19 SmartGit 试用过期
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示