首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ STL 仿函數詳解與應用實例

     編輯:關於C++

仿函數概念

仿函數是重載了 operator() 的類或結構體,其對象可像函數一樣調用。STL 算法(如 find_if, sort)接受仿函數作為策略參數,比函數指針更靈活(可攜帶狀態、內聯優化)。

基本定義與使用

template <class T>
struct GreaterThan {
    T threshold;
    GreaterThan(const T& t) : threshold(t) {}
    bool operator()(const T& val) const {
        return val >= threshold;
    }
};

// 使用
list<int> lst = {12, 178, 200};
auto it = find_if(lst.begin(), lst.end(), GreaterThan<int>(100));
if (it != lst.end()) cout << "found: " << *it << endl;

仿函數 vs 函數指針

兩者調用語法相同,但仿函數是類型,可作為模板參數傳遞,編譯器更易內聯優化;函數指針是運行期值,難以內聯。示例:

bool gt_func(int a, int b) { return a >= b; }
using FuncPtr = bool(*)(int,int);

struct GT {
    bool operator()(int a, int b) const { return a >= b; }
};

int main() {
    list<int> lst = {10, 110, 120};
    FuncPtr pf = gt_func;
    GT gt_obj;
    for (int v : lst) cout << pf(v, 100) << ' ';  // 函數指針調用
    for (int v : lst) cout << gt_obj(v, 100) << ' '; // 仿函數調用
}

標準庫預定義仿函數

<functional> 提供:

  • 算術:plus, minus, multiplies, divides, modulus, negate
  • 比較:equal_to, not_equal_to, greater, less, greater_equal, less_equal
  • 邏輯:logical_and, logical_or, logical_not

用法:sort(v.begin(), v.end(), greater<int>()) 降序排序。

自適應仿函數

繼承 unary_function 或 binary_function(C++11 已棄用)可提供 argument_type, result_type 等型別別名,方便 STL 內部萃取。

總結

仿函數是 STL 泛型編程核心:將操作封裝為可攜帶狀態的類型,支持模板參數傳遞、內聯優化、類型萃取。掌握自定義仿函數編寫與標準庫預定義仿函數使用,是高效使用 STL 算法的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved