zoukankan      html  css  js  c++  java
  • bind1st/bind2nd

    1. bind1st/bind2nd

    bind1st:  绑定器binder通过把二元函数对象的第一个实参绑定到一个特殊的值上将其转换成一元函数对象

    bind2nd: 绑定器binder通过把二元函数对象的第二个实参绑定到一个特殊的值上将其转换成一元函数对象

    例如:

    1 bool kPrint(int i, int j)
    2 {
    3 std::cout<< i << "---" << j << std::endl;
    4 return i>j;
    5 }
    6
    7  int _tmain(int argc, _TCHAR* argv[])
    8 {
    9 // 以下函数调用等价于调用kPrint(2,1)
    10   (std::bind1st(std::ptr_fun(kPrint), 2))(1);
    11 // 以下函数调用等价于调用kPrint(1,2)
    12 (std::bind2nd(std::ptr_fun(kPrint), 2))(1);
    13
    14 return 0;
    15 }

    说明:std::ptr_fun是将函数指针转换为仿函数指针。


    其它应用:

    计算数组中元素小于等于10的个数

    1 void funA()
    2 {
    3 using namespace std;
    4 vector<int> va;
    5 va.push_back(5);
    6 va.push_back(79);
    7 va.push_back(23);
    8 va.push_back(6);
    9 va.push_back(1);
    10 va.push_back(10);
    // 设c为va中的一个元素  
    // bind2nd(less_equal<int>(), 10) --> less_equal<int>(c, 10)
    11 int less10 = count_if( va.begin(), va.end(), bind2nd(less_equal<int>(), 10));
    12 cout << less10 << endl;
    13 }
    14
    15  // 以下是less_equal的实现部分
    16  template<class _Ty>
    17 struct less_equal
    18 : public binary_function<_Ty, _Ty, bool>
    19 { // functor for operator<=
    20   bool operator()(const _Ty& _Left, const _Ty& _Right) const
    21 { // apply operator<= to operands
    22   return (_Left <= _Right);
    23 }
    24 };
    25  


  • 相关阅读:
    基本输入输出函数
    变长参数表函数的编写
    一文精通Linux 命令行
    Linux 下的种种打包、压缩、解压命令
    GIT补丁怎么打?
    GIT 合并的冲突解决途径
    GIT 库整理方法
    GIT中常用命令详解1.reset
    霍夫曼编码及译码
    C语言链表实现队列
  • 原文地址:https://www.cnblogs.com/kekec/p/1858174.html
Copyright © 2011-2022 走看看