C++ 仿函数的运用范例: 泛型程式設計和封裝可重複使用的程式碼

仿函數(functor)是一種物件,其可以像函數一樣被調用,但是有自己的状态。一般來說,仿函數將物件的運算符 () 重載,使得該物件可以像函數一樣被呼叫。

仿函數可以用來封裝一些可重複使用的程式碼,或者將一個函數的行為自訂化。它們常常用於泛型程式設計中,使用者可以傳入仿函數以自訂某些行為。

示例:

#include <iostream>
#include <functional>

using namespace std;

struct MyFunctor
{
    int operator()(int x, int y) const
    {
        return x + y;
    }
};

int main()
{
    MyFunctor add;
    cout << add(3, 4) << endl;  // 輸出 7

    // 仿函數也可以作為 std::function 的參數
    function<int(int, int)> add2 = add;
    cout << add2(3, 4) << endl;  // 輸出 7

    return 0;
}

在這個示例中,MyFunctor 是一個仿函數類別,其將運算符 () 重載了。這樣就可以像呼叫函數一樣呼叫 MyFunctor 實例。


仿函數也可以像普通函數一樣被傳入 std::function 中。

仿函數常常用於泛型程式設計中,例如 STL 中的算法,它們可以接受一個仿函數作為參數,來自訂算法的某些行為。例如,我們可以使用仿函數實現自訂的排序演算法:

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

using namespace std;

struct MyComparator
{
    bool operator()(int x, int y) const
    {
        return x > y;
    }
};

int main()
{
    vector<int> v{ 3, 1, 4, 2 };
    sort(v.begin(), v.end(), MyComparator());  // 使用 MyComparator 進行排序

    for (int x : v)
        cout << x << " ";  // 輸出 4 3 2 1
    cout << endl;

    return 0;
}

在這個示例中,我們定義了一個仿函數類別 MyComparator,其將運算符 () 重載了。我們將 MyComparator 傳入 std::sort 中,以自訂排序的行為。

還有,仿函數也可以用來封裝一些可重複使用的程式碼。例如,我們可以使用仿函數封裝一個計算函數執行次數的功能:

#include <iostream>
#include <functional>

using namespace std;

struct CallCounter
{
    int count = 0;

    template <typename Func>
    auto operator()(Func func) -> decltype(func())
    {
        ++count;
        return func();
    }
};

int foo()
{
    return 42;
}

int main()
{
    CallCounter counter;
    cout << counter(foo) << endl;  // 輸出 42
}

在這個示例中,CallCounter 是一個仿函數類別,其將運算符 () 重載了。我們可以將任意函數傳入 CallCounter 中,並呼叫它,CallCounter 會計算函數被呼叫的次數。

另外,我們也可以使用仿函數來封裝一些可重複使用的程式碼,例如在每次呼叫函數之前或之後執行一些額外的操作。例如,我們可以使用仿函數封裝一個在函數執行前後輸出日誌的功能:

#include <iostream>
#include <functional>

using namespace std;

struct Logger
{
    template <typename Func>
    auto operator()(Func func) -> decltype(func())
    {
        cout << "Entering function" << endl;
        auto result = func();
        cout << "Exiting function" << endl;
        return result;
    }
};

int foo()
{
    cout << "Inside function" << endl;
    return 42;
}

int main()
{
    Logger logger;
    cout << logger(foo) << endl;  // 輸出
                                  // Entering function
                                  // Inside function
                                  // Exiting function
                                  // 42
    return 0;
}

在這個示例中,Logger 是一個仿函數類別,其將運算符 () 重載了。我們可以將任意函數傳入 Logger 中,並呼叫它,Logger 會在函數執行前後輸出日誌。

除了泛型程式設計和封裝可重複使用的程式碼之外,仿函數還可以用於實現類似函數指標的功能。例如,我們可以使用仿函數實現一個選擇排序演算法,讓使用者可以自訂排序的比較方式:

#include <iostream>
#include <vector>
#include <functional>

using namespace std;

template <typename T, typename Compare>
void selection_sort(vector<T>& v, Compare comp)
{
    for (int i = 0; i < v.size(); ++i)
    {
        int min_idx = i;
        for (int j = i + 1; j < v.size(); ++j)
            if (comp(v[j], v[min_idx]))
                min_idx = j;
        swap(v[i], v[min_idx]);
    }
}

int main()
{
    vector<int> v{ 3, 1, 4, 2 };

    // 使用仿函数 std::less<int> 進行升序排序
    selection_sort(v, less<int>());
    for (int x : v)
        cout << x << " ";  // 輸出 1 2 3 4
    cout << endl;

    // 使用仿函数 std::greater<int> 進行降序排序
    selection_sort(v, greater<int>());
    for (int x : v)
        cout << x << " ";  // 輸出 4 3 2 1
    cout << endl;

    return 0;
}

在這個示例中,我們寫了一個泛型函數 selection_sort,其可以排序任意類型的容器。使用者可以傳入一個仿函數 comp,來自訂排序的比較方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值