说明
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;
}
作者:book_02
链接:https://www.jianshu.com/p/f337f42822fe
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
请发表评论