C++ 函数指针、std::function 与 lambda
“把函数当值用"的三种写法:函数指针、std::function、lambda。包含语法拆解、三者对比、捕获方式速记与常见坑。 核心概念速查 概念 说明 关键点 函数指针 存函数地址的变量 C 风格,语法绕 std::function 通用函数包装器 C++11,可存 lambda/仿函数 lambda 匿名函数对象 C++11,现代首选 回调 函数指针的典型用途 事件、排序、遍历 捕获 lambda 使用外部变量 [ ] [&] [=] [x] 为什么需要函数指针 把"行为"作为参数传递,让代码更灵活。 // 没有函数指针: 每有一种排序规则就要写一个函数 void sort_ascending(int* arr, int n); void sort_descending(int* arr, int n); // 有函数指针: 一个排序函数,规则由调用方决定 void sort(int* arr, int n, bool (*compare)(int, int)); 函数指针基础语法 #include <iostream> // 定义两个比较函数 bool ascending(int a, int b) { return a < b; } bool descending(int a, int b) { return a > b; } // 参数是函数指针: bool (*compare)(int, int) void sort(int* arr, int n, bool (*compare)(int, int)) { for (int i = 0; i < n - 1; ++i) for (int j = i + 1; j < n; ++j) if (compare(arr[j], arr[i])) // 调用比较函数 std::swap(arr[i], arr[j]); } int main() { int arr[] = {3, 1, 4, 1, 5}; sort(arr, 5, ascending); // 传函数名(自动转成指针) // sort(arr, 5, &ascending); // 显式取地址也可以 sort(arr, 5, descending); for (int x : arr) std::cout << x << " "; return 0; } 语法记忆:bool (*compare)(int, int) —— *compare 是函数名,(int,int) 是参数,bool 是返回类型。不加括号 bool *compare(...) 就变成返回指针的函数了。 ...
豫公网安备41108202000982号