function adapter bind(C++11)
2017-06-06 08:31
176 查看
1.头文件
#include<functional>2.绑定
std::bind可以绑定[1]functions
[2]function objects
[3]member functions,_1必须是某个object地址
[4]data members,_1必须是某个object地址
返回一个function object ret,调用ret相当于调用上述1,2,3,或相当于去除4
http://www.cplusplus.com/reference/functional/bind/?kw=bind
// bind example #include <iostream> // std::cout #include <functional> // std::bind #include <vector> #include <algorithm> using namespace std; // a function: (also works with function object: std::divides<double> my_divide;) double my_divide (double x, double y) {return x/y;} struct MyPair { double a,b; double multiply() {return a*b;} }; int main () { using namespace std::placeholders; // adds visibility of _1, _2, _3,... // binding functions: auto fn_five = std::bind (my_divide,10,2); // returns 10/2 std::cout << fn_five() << '\n'; // 5 auto fn_half = std::bind (my_divide,_1,2); // returns x/2 std::cout << fn_half(10) << '\n'; // 5 auto fn_invert = std::bind (my_divide,_2,_1); // returns y/x std::cout << fn_invert(10,2) << '\n'; // 0.2 auto fn_rounding = std::bind<int> (my_divide,_1,_2); // returns int(x/y) std::cout << fn_rounding(10,3) << '\n'; // 3 MyPair ten_two {10,2}; // binding members: auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply() std::cout << bound_member_fn(ten_two) << '\n'; // 20 auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a std::cout << bound_member_data() << '\n'; // 10 vector<int> v{15, 37, 94, 50, 73, 58, 28, 98}; int n = count_if(v.cbegin(), v.cend(), not1(bind2nd(less<int>(), 50))); cout << "n=" << n << endl; // 5 auto fn_ = bind(less<int>(), _1, 50); cout << count_if(v.cbegin(), v.cend(), fn_) << endl; // 3 cout << count_if(v.begin(), v.end(), bind(less<int>(), _1, 50)) << endl; //3 cout << count_if(v.begin(), v.end(), bind(less<int>(), _1, 50)) << endl; return 0; }
相关文章推荐
- C++11 std::bind std::function 高级使用方法
- c++11特性与cocos2d-x 3.0之std::bind与std::function
- C++11 FAQ中文版:std::function 和 std::bind
- C++11 FAQ中文版:std::function 和 std::bind
- 利用C++11的function和bind简化类创建线程
- c++11基础学习(2)std::bind与std::function特性
- C++11 std::function、std::bind和lambda表达式
- c++11特性与cocos2d-x 3.0之std::bind与std::function
- C++11 FAQ中文版:std::function 和 std::bind
- 【C++11】新特性——std::function 和 std::bind
- C++11 std::function、std::bind
- C++11 std::bind std::function 高级用法
- C++11新特性之八:bind和function
- c++11特性与cocos2d-x 3.0之std::bind与std::function
- c++11中的bind和function
- C++11新特性应用--实现延时求值(std::function和std::bind)
- C++11 中std::function和std::bind的用法
- C++0x FAQ中文版:std::function 和 std::bind - [C++11 FAQ]
- 【C++11】新特性——function、bind以及lamda表达式
- C++11 中std::function和std::bind的用法