bind1st与bind2nd函数解析

  1. // bind1st和bind2nd函数把一个二元函数对象绑定成为一个一元函数对象。  
  2. // 但是由于二元函数对象接受两个参数,在绑定成为一元函数对象时需要将原来两个参数中的一个绑定下来。  
  3. // 也即通过绑定二元函数对象的一个参数使之成为一元函数对象的。  
  4. // bind1st是绑定第一个参数,bind2nd则是绑定第二个参数。  
  5. // 我个人喜欢用bind2nd,这样子代码读起来更顺。  
  6.   
  7. class greaterthan5: std::unary_function<intbool>  
  8. {  
  9. public:  
  10.     result_type operator()(argument_type i)  
  11.     {  
  12.         return (result_type)(i > 5);  
  13.     }  
  14. };  
  15.   
  16. void test_func_bind()  
  17. {  
  18.     std::vector<int> v1;  
  19.     std::vector<int>::iterator Iter;  
  20.   
  21.     int i;  
  22.     for (i = 0; i <= 5; i++)  
  23.     {  
  24.         v1.push_back(5 * i);  
  25.     }  
  26.   
  27.     std::cout << "The vector v1 = ( " ;  
  28.     std::copy(v1.cbegin(), v1.cend(), std::ostream_iterator<int>(std::cout, " "));  
  29.     std::cout << ")" << std::endl;  
  30.   
  31.     // Count the number of integers > 10 in the vector  
  32.     std::vector<int>::iterator::difference_type result1a;  
  33.     result1a = count_if(v1.begin(), v1.end(), bind1st(std::less<int>(), 10));  
  34.     std::cout << "The number of elements in v1 greater than 10 is: "  
  35.         << result1a << "." << std::endl;  
  36.   
  37.     // Compare: counting the number of integers > 5 in the vector  
  38.     // with a user defined function object  
  39.     std::vector<int>::iterator::difference_type result1b;  
  40.     result1b = count_if(v1.begin(), v1.end(), greaterthan5());  
  41.     std::cout << "The number of elements in v1 greater than 5 is: "  
  42.         << result1b << "." << std::endl;  
  43.   
  44.     // Count the number of integers < 10 in the vector  
  45.     std::vector<int>::iterator::difference_type result2;  
  46.     result2 = count_if(v1.begin(), v1.end(), bind2nd(std::less<int>(), 10));  
  47.     std::cout << "The number of elements in v1 less than 10 is: "  
  48.         << result2 << "." << std::endl;  
  49. }  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值