常規函數適配器,成員函數適配器

來源:互聯網
上載者:User

stl演算法中,可以使用函數指標以及仿函數傳遞演算法.

那麼為什麼還需要常規函數適配器呢?

因為,常規函數適配器無"配接能力"

例子:

/*  * File:   main.cpp * Author: Vicky.H * Email:  eclipser@163.com */#include <iostream>#include <vector>#include <algorithm>#include <functional>class A {public:    int id;    A() { }    A(int id) : id(id) { }};// 普通函數,需要2個參數!但,for_each,find_if等stl演算法,只提供1個參數,第2個參數需要std::bind2nd提供bool id_eq(const A* a, const int& id) {    return a->id == id;}/* *  */int main(void) {    A* aa[] = {new A(1), new A(2), new A(3), new A(4), new A(5)};    std::vector<A*> av(aa, aa + 5);    const int id = 5;    // 我們需要查詢id為5的A    // std::find_if(av.begin(), av.end(), id_eq);    // 注意,我們沒辦法為id_eq傳遞第2個參數為5,顧會出現  error: too few arguments to function,這也需要普通函數適配器的原因    // std::ptr_fun(id_eq);    // std::bind2nd(std::ptr_fun(id_eq), id);    std::vector<A*>::iterator it = std::find_if(av.begin(), av.end(), std::bind2nd(std::ptr_fun(id_eq), id));    std::cout << (*it)->id << std::endl;        // 銷毀指標...    for (int i = 0; i < av.size(); i++) delete av[i];    return 0;}

 

5
 

 

成員函數適配器:

/*  * File:   main.cpp * Author: Vicky.H * Email:  eclipser@163.com */#include <iostream>#include <algorithm>#include <functional>#include <vector>class A{public:virtual void display() = 0;};class B : public A{public:virtual void display() {std::cout << "B" << std::endl;} virtual ~B(){}};class C : public A{public:void display() {std::cout << "C" << std::endl;}};class D : public B{public:void display() {std::cout << "D" << std::endl;}};/* *  */int main(void) {    std::vector<A*> pAV;        pAV.push_back(new B);    pAV.push_back(new C);    pAV.push_back(new D);    pAV.push_back(new B);        for (int i = 0; i < pAV.size(); i++) {        pAV[i]->display();    }    std::cout << "---------------------------" << std::endl;        /**為什麼不能同全域函數一樣直接傳遞函數名而成員函數必須以  &類名::函數名  的方式,因為需要考慮static成員函數的情況!*/    std::for_each(pAV.begin(),pAV.end(), std::mem_fun(&A::display) /* std::mem_fun_ref(&A::display)由於我們建立的指標,這裡不能使用處理對象的成員函數適配器*/);    return 0;}

B
C
D
B
---------------------------
B
C
D
B

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.