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
                  
                  
                  
                  
                            
本文通过两个实例深入解析了STL中的函数适配器如何解决特定问题:一是使用std::bind2nd来适配普通函数以供单参数算法使用;二是利用成员函数适配器std::mem_fun实现对不同对象成员函数的统一调用。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					12
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            