函数指针
- 函数指针的好处在于可以减少一部分代码
- 函数指针在函数参数中的写法见void bulleSort函数第三个参数, **即 bool (*pfun)(int x, in y) **
- 函数指针的使用方式见bulleSort函数if语句内,此处表示使用提前定义的bool函数
- 函数指针的传参方式见主函数,调用bulleSort函数时,其函数内第三个参数此时决定了bulleSort函数使用哪个bool函数
#include<iostream>
using namespace std;
bool max(int x, int y) { return x > y; }
bool min(int x, int y) { return x < y; }
void bulleSort(int arr[], int len, bool(*pfun)(int x, int y))
{
int temp;
for (int i = 0; i < len-1; ++i)
{
for (int j = 0; j < len - i - 1; ++j)
{
if (pfun(arr[j + 1], arr[j]))
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int arr[10] = { 1,2,323,223,344,563,23,6572,12 };
cout << "用来说明函数指针-从大到小排序" << endl;
bulleSort(arr, 10, max);
for (auto s : arr)
{
cout << s << "\t";
}
cout << endl << endl << "用来说明函数指针-从小到大排序" << endl;
bulleSort(arr, 10, min);
for (auto s : arr)
{
cout << s << "\t";
}
cin.get();
return 0;
}
指针函数