• 适配器


    适配器

    adapters是二十三种设计模式之一,STL所提供的配接器中,改变仿函数的接口者,我们称为function adapter。改变容器接口者,我们称为container adapter。改变迭代器接口者,我们称为iterator adapter。

    容器适配器:stack queue

    如下图所示:

    stack中内含了一个deque,deque可能含有100个函数,但是呢,stack对其进行了一种改造,只开放6个接口,对函数名字的改变也称之为一种改造。

    将内含容器(deque)的特性改造为具有自己(stack)的特性的接口。

    函数适配器 bind2nd

    新型适配器 bind

    bind可以绑定:

    • functions
    • function objects
    • member functions ,必须是某个object地址
    • data members ,必须是某个object地址
    using namespace std::placeholders; /占位符 _1,_2,_3
    double my_divide(double x, double y) {
        return x /y;
    }
    auto fn_five = bind(my_divide,10,2);
    cout <<fn_five()
    
    auto fn_half = bind(my_divide,_1,_2);
    cout << fn_half(10,2) << endl;
    
    //bind也可以绑定一个参数,例如下面的int,就是返回类型是int
    auto fn_rounding = bind<int>(my_divide,1_,_2);
    cout <<fn_rounding(10,3) << endl; 
    
    //绑定member functions,必须是某个object地址
    
    //定义类MyPair
    struct MyPair {
      double a, b;
      double multply() {return a * b;}
    };
    //定义类的实例
    MyPair ten_two {10,2};
    auto bound_memfn = bind(&MyPair::multiply,_1); //returans x.multply(),其实有个参数是this
    cout << bound_menfn(ten_two) << endl;
    

    绑定成员数据

    auto bound_memdata = bind(&MyPair::a,ten_two);
    cout << boud_memdata() << endl;
    

    //求不小于50的数

    vector<int> v{15,78,87,781};
    int n = count_if(v1.cbegin(),v.cend(), not1(bind2nd(less<int>(),50)));
    cout << "n="  << n << endl;
    
    //使用bind的方式求
    auto fn_ = bind(less<int>(),_1,50);
    cout << count_if(v.cbegin(),v.cend(),fn_)<<endl;
    

    迭代器适配器

  • 相关阅读:
    Duff and Meat(贪心)
    Duff and Meat(贪心)
    Eugeny and Array(水题,注意题目描述即可)
    Eugeny and Array(水题,注意题目描述即可)
    HDU-2588-GCD (欧拉函数)
    HDU-2588-GCD (欧拉函数)
    再谈欧拉函数
    再谈欧拉函数
    容斥定理及浅略介绍
    Vue
  • 原文地址:https://www.cnblogs.com/ccpang/p/12284029.html
Copyright © 2020-2023  润新知