Home >Backend Development >C++ >How to replace function pointer with C++ lambda expression?
Replacing function pointers with lambda expressions improves readability, reduces boilerplate code, and increases reusability. Specifically, lambda expressions use the following syntax: [capture list](parameter list) -> return type {body}, and can be used in practical cases such as vector sorting to improve code simplicity and maintainability.
Replace function pointers with C Lambda expressions
Lambda expressions were introduced in C++11, providing a simple Method to define anonymous functions or function pointers. Replacing function pointers with lambda expressions has many benefits, including:
Syntax
The syntax of lambda expression is as follows:
[capture list](parameter list) -> return type { body }
Example
The following is an example of replacing a function pointer with a lambda expression:
// 函数指针方式 int compare(int a, int b) { return a - b; } // Lambda 表达式方式 auto compare = [](int a, int b) { return a - b; };
Practical case: sorting vectors
We can see the advantages of lambda expressions in a practical case:
#include <vector> #include <algorithm> int main() { std::vector<int> v = { 1, 5, 3, 2, 4 }; // 用 lambda 表达式对向量进行排序 std::sort(v.begin(), v.end(), [](int a, int b) { return a < b; }); // 打印排序后的向量 for (int x : v) { std::cout << x << " "; } return 0; }
In this case, lambda expressions are used to define a comparison function that is used to Sort vectors. There is no need to define separate functions, and the code is simpler and easier to understand.
The above is the detailed content of How to replace function pointer with C++ lambda expression?. For more information, please follow other related articles on the PHP Chinese website!