【from wiki】 A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call. Such an invocation is also known as an “indirect” call, because the function is being invoked indirectly through a variable instead of directly through a fixed identifier or address.
Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.
重点已经在上面标出来了,函数指针的作用之一是简化代码。
那么c++标准委员会仅仅是为了让我们写clean code吗?
Obviously not! Another use for function pointers is setting up “listener” or “callback” functions that are invoked when a particular event happens.
#include <utility> // for std::swap #include <iostream> // Note our user-defined comparison is the third parameter void selectionSort(int *array, int size, bool (*comparisonFcn)(int, int)) { // Step through each element of the array for (int startIndex {0}; startIndex < (size - 1); ++startIndex) { // bestIndex is the index of the smallest/largest element we've encountered so far. int bestIndex {startIndex}; // Look for smallest/largest element remaining in the array (starting at startIndex+1) for (int currentIndex{ startIndex + 1 }; currentIndex < size; ++currentIndex) { // If the current element is smaller/larger than our previously found smallest if (comparisonFcn(array[bestIndex], array[currentIndex])) { // COMPARISON DONE HERE // This is the new smallest/largest number for this iteration bestIndex = currentIndex; } } // Swap our start element with our smallest/largest element std::swap(array[startIndex], array[bestIndex]); } } // Here is a comparison function that sorts in ascending order bool ascending(int x, int y) { return x > y; // swap if the first element is greater than the second } // Here is a comparison function that sorts in descending order bool descending(int x, int y) { return x < y; // swap if the second element is greater than the first } // This function prints out the values in the array void printArray(int *array, int size) { for (int index{ 0 }; index < size; ++index) { std::cout << array[index] << ' '; } std::cout << '\n'; } int main() { int array[9] { 3, 7, 9, 5, 6, 1, 8, 2, 4 }; // Sort the array in descending order using the descending() function selectionSort(array, 9, descending); printArray(array, 9); // Sort the array in ascending order using the ascending() function selectionSort(array, 9, ascending); printArray(array, 9); return 0; }