我正在尝试为我的作业实现通用排序方法,这就是我所得到的:
void mySort(int(*condition)(TElement,TElement), DynamicArray *arr)
{
if (arr == NULL)
return;
if (arr->elems == NULL)
return;
int i, j;
for (i = 0; i < arr->length - 1; i++)
for (j = i; j < arr->length; j++)
if (condition(arr->elems[i], arr->elems[j]) == 0)
{
TElement *aux = arr->elems[i];
arr->elems[i] = arr->elems[j];
arr->elems[j] = aux;
}
}
我的条件结构定义如下:
typedef int(*condition)(Country*, Country*);
//我有一个“国家”数组,我需要以各种方式对它们进行排序
我遇到的麻烦是在哪里编写实际条件方法(也许在我的存储库模块中)以及如何定义它。 我尝试过这样的:
int conditionAsByPop(Country* c1, Country* c2) \\Condition to sort ascending by population
{
if (c1->population > c2->population)
return 1;
return 0;
}
但我不知道如何实际调用它......
void sortAsByPop(CountryRepo* v)
{
mySort(conditionAsByPop(????), v);
}
谢谢!
最佳答案
您将向 mySort
传递一个指向函数的指针作为一个参数,以用于比较。在 C 语言中,函数名相当于函数指针,而不是变量。基本上,您必须定义比较函数,例如 conditionAsByPop
,并使用该函数调用 mySort
:
void sortAsByPop(CountryRepo* v)
{
mySort(conditionAsByPop, v);
}
关于c - 实现通用排序功能时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49419194/