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