c - 实现通用排序功能时遇到问题

标签 c

我正在尝试为我的作业实现通用排序方法,这就是我所得到的:

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/

相关文章:

数组内字符串中的 C 索引

c++ - 使用 Eclipse CDT 运行 "dynamic"参数

c - 在 C 中一次输出一个字母的文本

c - 为什么我收到警告 excess initializers are ignored?

c - 将 int Unicode 代码点保存到 UTF-8 文件

c - 在 for 循环中交换语句

c - c中的指针作为结构体变量

c - 在 C 中缩短我的代码

c - realloc() 如何工作?

在嵌入式编程中 main 启动之前检查 GPIO 的状态