所謂 functor 簡單來說就是在 class 內 overload 小括弧

 

例如

#include <iostream>
#include <algorithm>

class functor
{
    public:
        bool operator ()(const int &_a, const int &_b)
        {
            compareTimes += 1;
             return _a > _b;
         }

         int get_compareTimes() const{ return compareTimes; }


    private:
        int compareTimes = 0;
};

using namespace std;

int main()
{
    int arr[10];
    for(int i = 0; i<10; i++)
        arr[i] = i;


    functor f;
    for(int i = 0; i<10; i++)
        for(int j = 0; j<10-i-1; j++)
            if( ! f(arr[j], arr[j+1]) )
                swap(arr[j], arr[j+1]);


    cout << "sorted : ";
    for(int i: arr)
        cout << i << " ";
    cout << endl;

    cout << "total compare times: " << f.get_compareTimes() << endl;

    return 0;
}

 

優點是可以更方便的紀錄其它資訊,像是 compareTimes

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大神(偽) 的頭像
    大神(偽)

    大神的世界

    大神(偽) 發表在 痞客邦 留言(0) 人氣()