浅析C++仿函数

何为仿函数

仿函数这个词经常出现在C++的模板库(STL)里,就自己浅陋的理解,仿函数就是能够实现跟函数一样的功能的东西,通常以结构体或类的形式呈现出来。实现的关键就是重载()这个操作符。

为什么要用仿函数

我们知道,函数可以作为参数来传递,我们知道可以用函数指针来实现。而仿函数是另一种方式来实现这样的功能。STL模板库中,大量使用这种技巧。

代码举例说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
*我们实现对结构体Node对象的比较
**/
#include <iostream>
#include <vector>
#include <functional>
using namespace std;

/**
*结构体Node
**/
struct Node {
    int val;
    Node(int v):val(v){

    }
};

/**
*基于二元操作符的仿函数实现
**/
struct Compare:binary_function<Node*, Node*, bool> {
  /**
 * 重载()操作符
 **/
    bool operator()(Node &a,Node &b){
        return a.val<b.val;
    }
};

int main(int argc, const char * argv[]) {
    Node n1(2);
    Node n2(3);
    cout<<Compare()(n2,n1)<<endl;
    return 0;
}

在STL中使用举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* for_each函数实现的源码就用到了仿函数,Functor就是一个仿函数,它作为for_each的一个参数
**/

template < typename Iterator, typename Functor >
void for_each( Iterator begin, Iterator end, Fucntor func )
{
for( ; begin!=end; begin++ )
func( *begin );
}


/**
*使用for_each打印vector所有元素
**/

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

struct Print :unary_function<int,void>{
    void operator()(int i){
        cout<<i<<endl;
    }
};

int main(int argc, const char * argv[]) {
   vector<int> ve = {1,2,3};
   for_each(ve.begin(), ve.end(), Print());
  return 0;
}

Comments