[C++] 仿函數 Functor

與小強在討論list.sort()的時候(見如下程式碼)

#include <iostream>
#include <list>
using namespace std;

struct structB
{
int x;
};

typedef structB STRUCT_B;

bool compare(STRUCT_B & a, STRUCT_B & b)
{
return a.x < b.x;
}

class A
{
public:
STRUCT_B m_ID;
void method()
{
list<STRUCT_B> MyList;
MyList.sort(compare);
}
};

int main(int argc, char * argv[])
{
A MyObjA;
MyObjA.method();
return 0;
}

發現sort()裡面的compare 函數可以有更多型式,如下程式:


#include <iostream>
#include <list>
using namespace std;

struct structB
{
int x;
};

typedef structB STRUCT_B;

class compare
{
public:
bool operator()(STRUCT_B & a ,STRUCT_B & b)
{
return a.x < b.x;
}
};

class A
{
public:
STRUCT_B m_ID;
void method()
{
list<STRUCT_B> MyList;
MyList.sort(compare());
}
};

int main(int argc, char * argv[])
{
A MyObjA;
MyObjA.method();
return 0;
}

便對於operator() 這個東西感到好奇。就上網搜尋了一下,找到這一篇精細的講解:

C++ 仿函数(Functor)

大意是講說 functor 把class或structure 當成一般函數來處理,所以才可以有這種特殊的寫法。

這篇文章中,也對於Functor的優缺點做了精闢的分析,有興趣的讀者可以前往觀看。

另外,再補上國外一個關於Functor的教學:

This entry was posted in 程式設計. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *