C++ 函數適配器與容器適配器adapter

C++ 函數適配器與容器適配器adapter


前言

我們在日常生活中需給電腦充電,電腦時無法直接承受強大的電壓,所以我們需要使用一個適配器來對電壓進行轉換,讓我們的電腦能夠通過適配器來充電。
在C++ STL中,我們想使用一個已經規定好的模板,但是這個模板需要做一些轉換才能供我們使用,這便有了適配器的出現。
下面主要講

  • 函數適配器 bind1nd、bind2nd
  • 容器適配器 stack、queue、priority_queue

一.函數適配器 bind1nd、bind2nd

如果想使用某一個函數,但是這個函數又並不完全符合我們使用的要求,那麼我們就需要使用函數適配器bind1st, bind2nd,用來返回我們想要使用的函數

另外 bind的用法過多,參考另外一篇文章:bind函數適配器、利用bind回調實現無繼承多態、men_fn將成員函數轉換爲函數對象

struct pred:public binary_function<int, int, bool>{
    bool operator()(const int& lhs, const int& rhs)const{
        if (lhs >= rhs){
            cout << lhs << endl;
            return true;
        }
        return false;
    }    
};

//例如,當vector中元素>=5時,將其打印出來
void test1(){
    vector<int> vec{1,3,5,6,7,8};
    for_each(vec.begin(), vec.end(), bind2nd(pred(), 5));    
}

//例如,刪除vector中>=5的元素
void test2(){
    vector<int> vec{1,3,5,6,7,8};
    vec.erase(remove_if(vec.begin(), vec.end(), bind2nd(std::greater_equal<int>(), 5)), vec.end());
    for (auto& e : vec)
        cout << e << endl;
}

二.容器適配器

stack、queue、priority_queue均爲容器適配器
stack 與 queue 的標準模板爲deque, stack與queue相當於只是實現的deque的一部分功能,不用再重新寫函數了, 所以也就被成爲容器適配器
priority_queue 的標準模板爲vector,但是優先隊列的邏輯實現是和最大堆,最小堆一致,底層仍然是用的二叉堆來實現

class Point{
public:
    Point(int x, int y)
    :_x(x)
    ,_y(y)
    {
        _sum = x + y;
    }
    int _x;
    int _y;
    int _sum;
    friend ostream& operator<<(ostream& os, const Point& lhs);
    
};
ostream& operator<<(ostream& os, const Point& lhs){
    os << lhs._sum;
    return os;
}

struct myCompare{
    bool operator()(const Point& lhs, const Point& rhs){
        return lhs._sum > rhs._sum;
    }
};

void test3(){
    priority_queue<Point, vector<Point>, myCompare> myque;
    myque.push(Point(1,1));
    myque.push(Point(2,2));
    myque.push(Point(3,3));

    while (!myque.empty()){
        cout << "Now the highest priority is :" << myque.top() << endl;
        myque.pop();
    }
}

int main(){
    test3();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章