Home > Article > Backend Development > The definition and usage of function pointers in C++
A function pointer in C is a variable pointing to a function, allowing the function to be passed as a parameter. Using function pointers you can define them, assign function names or lambda expressions to them, and call them like normal functions. Function pointers are widely used in function operators, such as sort function operators, allowing sorting functions to be created and used at runtime.
A function pointer is a variable that points to a function. It provides the ability to pass functions as arguments and the flexibility of calling functions at runtime.
In C, a function pointer can be defined as follows:
returntype (*function_ptr_name)(param_type1, param_type2, ...);
For example, define a pointer to a function that accepts two integer parameters and returns an integer:
int (*add_pointer)(int, int);
You can initialize a function pointer by assigning the function name to it:
add_pointer = add; // 假设 add 是一个接收两个整数并返回整数的函数
Alternatively, you can use a lambda expression to create a function pointer:
add_pointer = [](int a, int b) -> int { return a + b; };
You can call a function pointer just like a normal function:
int result = add_pointer(10, 20);
A common application of function pointers is functions Converter, which allows the creation and use of sorting functions at runtime. For example, the following code uses function pointers to implement std::sort
with comparison functions:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {3, 1, 5, 2, 4}; // 定义比较函数指针 int (*compare_func)(int, int) = [](int a, int b) -> bool { return a < b; }; // 使用函数指针排序 std::sort(numbers.begin(), numbers.end(), compare_func); // 输出排序后的结果 for (const auto& number : numbers) { std::cout << number << ' '; } return 0; }
The above is the detailed content of The definition and usage of function pointers in C++. For more information, please follow other related articles on the PHP Chinese website!