• bind2nd使用


    template <class Operation, class T>
    binder2nd<Operation> bind2nd (const Operation& op, const T& x);

    bind2nd是一个函数配接器,目的是将二元仿函数转换为一元仿函数,可以将第二参数传给第一参数(二元仿函数),作为二元仿函数的第二参数。常用于泛型算法中的谓词出现。

    使用1.

    #include <functional>
    struct GT : public binary_function<string, int, bool> {
      bool operator() (const string& s, const int& len) const {
        return s.size() >= len;
      }
    };
    
    int main() {
      vector<string> vec;
      string word;
      while(cin >> word && (word.compare("#") != 0)) {
        vec.push_back(word);
      }
      int m = count_if(vec.begin(), vec.end(), bind2nd(GT(), 3));
      cout << "gt 3:" << m << endl;
      return 1;
    }

    定义一个仿函数,继承binary_function。注意的是重载函数() 必须声明为const、参数也为const,与bind2nd类型保持一致,否则编译通不过。

    使用2.

    bool GTLen(string s,int len){
      return s.size() >= len;
    }
    int i = count_if(vec.begin(), vec.end(), bind2nd(ptr_fun(GTLen),4));
    cout << "gt 4:" << i << endl;

    定义一个二元函数,利用ptr_fun函数配接器,将函数指针转换为仿函数。此方法简单,省略了结构体或类的定义。

    template <class Arg, class Result>
      pointer_to_unary_function<Arg,Result> ptr_fun (Result (*f)(Arg));
    
    template <class Arg1, class Arg2, class Result>
      pointer_to_binary_function<Arg1,Arg2,Result> ptr_fun (Result (*f)(Arg1,Arg2));




  • 相关阅读:
    开发工具
    人脸识别
    mysql 3813:Column check constraint 'tb_course_chk_3' references other column.
    sleep()和wait()的异同
    线程通信——wait(),notify(),notifyAll()
    对王建民老师的评价&JAVA结课自我总结
    JAVA学习日报 12/19
    JAVA学习日报 12/18
    JAVA学习日报 12/17
    JAVA学习日报 12/11
  • 原文地址:https://www.cnblogs.com/whuqin/p/4982029.html
Copyright © 2020-2023  润新知