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

STL函數對象適配器ptr_fun用法示例

     編輯:C++ 入門

ptr_fun作用

將**普通函數指針**轉換為**函數對象**(可調用對象),使其能用於STL算法要求函數對象的場合。

兩個版本

  • `ptr_fun(Result (*)(Arg))` → `pointer_to_unary_function`
  • `ptr_fun(Result (*)(Arg1, Arg2))` → `pointer_to_binary_function`

代碼示例


#include 
#include 
#include 

int u_func(int x) { return x * 2; }
int b_func(int x, int y) { return x + y; }

int main() {
    // 一元函數適配
    std::pointer_to_unary_function uf = std::ptr_fun(u_func);
    std::cout << uf(5) << std::endl; // 10
    std::cout << std::ptr_fun(u_func)(5) << std::endl; // 直接用
    
    // 二元函數適配
    std::pointer_to_binary_function bf = std::ptr_fun(b_func);
    std::cout << bf(3, 4) << std::endl; // 7
    std::cout << std::ptr_fun(b_func)(3, 4) << std::endl; // 直接用
    
    // 實際應用:配合STL算法
    int arr[] = {1,2,3,4,5};
    std::transform(arr, arr+5, arr, std::ptr_fun(u_func)); // 每元素*2
    // arr 變為 {2,4,6,8,10}
}

現代C++替代方案

C++11起推薦使用 **lambda表達式** 或 **`std::function`** / **`std::bind`**:


// Lambda(更直觀、無額外開銷)
std::transform(arr, arr+5, arr, [](int x){ return x*2; });

// std::function
std::function f = u_func;
std::transform(arr, arr+5, arr, f);

注意事項

  • `ptr_fun` 在 C++11 中**棄用**,C++17 移除
  • 僅適用於**自由函數/靜態成員函數**,不適用於非靜態成員函數(需 `std::mem_fun`/`std::bind`)
  • 現代代碼優先使用 lambda
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved