#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
using namespace std::placeholders;
/**
*
* 原来只能使用bind1st bind2nd绑定
*
* c++11使用bind即可
* using namespace std::placeholders;
* bind可以绑定
* 1、functions
* 2、function objects
* 3、member functions _1必须是某个object地址
* 4、data members _1必须是某个object地址
*
*/
double my_divide(double x, double y)
{
return x / y;
}
void myprint(int a, long b, string c)
{
cout << "a: " << a << "b: " << b << "c: " << c << endl;
}
struct myPair
{
myPair(int x, int y) : a(x), b(y) {}
double a, b;
double multiply() { return a * b; }
};
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 6, 6, 1, 2, 31};
sort(arr, arr + 11, [](int a, int b)
{ return a > b; });
for (int i : arr)
cout << i << " ";
cout << endl
<< "================" << endl;
// bind1st作用,绑定less<int>的第一个参数不动
//自己给第一个参数赋值,然后在过程中不断更换第二个参数并与第一个自己给的参数进行对比
cout << count_if(arr, arr + 11, bind1st(less<int>(), 2.5)) << endl;
// bind2nd和bind1st类似,只是将第二个参数绑定,和第一个参数对比
//下两行结果一样
cout << count_if(arr, arr + 11, bind2nd(less<int>(), 2.5)) << endl;
cout << count_if(arr, arr + 11, bind1st(greater<int>(), 2.5)) << endl;
cout << count_if(arr, arr + 11, not1(bind2nd(less<int>(), 2.5))) << endl;
// binder2nd通过less<int>(),确定second_argument_type为int,将int(2.5)=2
cout << "=================================" << endl;
//==========================================================================
// c++11
// binding functions
auto fn_five = bind(my_divide, 10, 2);
cout << fn_five() << endl;
auto fn_half = bind(my_divide, _1, 2); //绑定第一个参数
cout << fn_half(10) << endl; //输入第一个参数
auto fn_invert = bind(my_divide, _2, _1); //依次转为第二个和第一个参数
cout << fn_invert(10, 3) << endl; // 3/10=0.3
auto fn_rounding = bind<int>(my_divide, _1, _2); //<>内部绑定他的返回值
cout << fn_rounding(10, 3) << endl; // int(10/3)=3
auto myprint_auto = bind /* <void> */ (myprint, _3, _2, _1);
myprint_auto("string", 123000000, 10);
// binding members
myPair ten_two{10, 2};
auto bound_memfn = bind(&myPair::multiply, _1); // multiply()虽然没有参数,但是成员函数其实有 argument:this
cout << bound_memfn(&ten_two) << endl; //实际上相当于调用,_1.multiply(); 即ten_two.multiply();
cout << bound_memfn(ten_two) << endl;
auto bound_memdata = bind(&myPair::a, ten_two);
cout << bound_memdata() << endl; //调用ten_two.a;
auto bound_memdata2 = bind<int>(&myPair::b, _1); //_1接受一个myPair对象,绑定b
cout << bound_memdata2(ten_two) << endl;
cout << bound_memdata2(new myPair(1, 11)) << endl;
cout << "=================================" << endl;
auto fn_less = bind(less<int>(), _1, 3);
cout << count_if(arr, arr + 11, fn_less) << endl; //计算小于3的个数
auto fn_greater = bind(greater<int>(), _1, 3);
cout << count_if(arr, arr + 11, fn_greater) << endl; //计算大于3的个数
vector<int> v(arr, arr + 11);
cout << count_if(v.begin(), v.end(), fn_less) << endl;
cout << count_if(v.begin(), v.end(), bind(less<int>(), _1, 6)) << endl;
}
bind1st和bind2nd以及c++11 bind 的用法
最新推荐文章于 2024-03-15 13:19:09 发布