zoukankan      html  css  js  c++  java
  • 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学习笔记
    MySQL的MySQL 的JDBC的安装与使用
    numpy的使用方法
    Linux命令
    MongoDB数据库
    爬虫请求库之selenium
    解析库beautifulsoup
    Requests属性
    正向代理、反向代理
    爬虫基本原理
  • 原文地址:https://www.cnblogs.com/whuqin/p/4982029.html
Copyright © 2011-2022 走看看