int LocateElem_Sq(Sq_List L,ElemType e,Status(*compare)(ElemType,ElemType))
{
int index = -1; // 没找到,返回-1;从0下标开始
Sql_List *ptr = &L; // 用于遍历的指针
while(ptr->next != NULL) // 停止遍历条件
{
++index; // 索引自增
if(*compare(ptr->data, e) == TRUE) // 调用函数参数,比较大小
break; // 找到第一个,则跳出循环
}
return index; // 返回索引值
}
在线性表里有一个这样一个查找的操作,我一开始一直不理解为什么第三个参数要把一个函数传入
之后类比C++泛型的操作,就可以说的通了
如:函数作为参数的情况在C++里特别有用,比如对一个把一个数组中的所有元素都乘以2,
//
void arrMutli2(void func(int & ), int arr[], int n)
{
for(int i = 0; i < n; ++i)
func(arr[i]);
}
//
void func(int &x)
{
x *= 2;
}
函数作为参数通常用于这种情况,即对一个数据结构的中的每个元素(如arr[i])都执行一个特定函数(如func)操作。C++标准库(STL)中就有很好的体现,如使用头文件algorithm中的排序函数sort时就需要传入一个比较函数作为参数。
#include <algorithm> // 包含头文件
using namespace std;
bool cmp(int x, int y)
{
return x > y;
}
int main()
{
const int n = 5;
int arr[n] = {5, 7, 3, 1, 3};
// 排序,第三个参数为函数
sort(arr, arr + n, cmp);
return 0;
}