C qsort 与非全局查找表比较

标签 c lookup-tables qsort

我正在尝试重构一个当前是独立 C 程序的实用程序,以便我可以创建一个可重用的库。它包括根据全局数组中的相应值对数组进行排序的步骤。

// Global lookup table
double *rating;

// Comparator using lookup
int comp_by_rating(const void *a, const void *b) {
  int * x = (int *) a;
  int * y = (int *) b;
  if (rating[*x] > rating[*y])
    return 1;
  else if (rating[*x] < rating[*y])
    return -1;
  else
    return 0;
}

int main() {
  int* myarray;
  // ...
  // initialize values of local myarray and global rating
  // ...

  qsort(myarray, length_myarray, sizeof(int), comp_by_rating);
  // ...
  return 0;
}

有没有办法避免将评级查找表全局化?我传统上是一个 C++ 人,所以我的第一个想法是仿函数,但我必须留在 C 中,所以我想我没有仿函数。我也无法将 int *myarray 替换为保存每个项目评级的结构数组,因为其他代码需要当前形式的数组。我还有其他选择吗?

最佳答案

I also can't replace int *myarray with an array of structs holding the rating for each item, since other code requires the array in its current form.

您可以临时替换排序,调用qsort,并将结果收回到原始数组中:

struct rated_int {
    int n;
    double r;
};

struct rated_int *tmp = malloc(length_myarray * sizeof(struct rated_int));
for (int i = 0 ; i != length_myarray ; i++) {
    tmp[i].n = myarray[i];
    tmp[i].r = ratings[myarray[i]];
}
qsort(tmp, length_myarray, sizeof(struct rated_int), comp_struct);
for (int i = 0 ; i != length_myarray ; i++) {
    myarray[i] = tmp[i].n;
}
free(tmp);

这样,其余代码就会将 myarray 视为整数数组。

关于C qsort 与非全局查找表比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897618/

相关文章:

c++ - 使用 cstdlib 中的 qsort

c++ - 如何对一组对进行排序?

c - qsort 的结构数组不工作

c - 使用 MinGW 构建依赖于 Visual Studio CRT (msvcr110.dll) 而非 Windows CRT (msvcrt.dll) 的 Windows DLL

c - 接收电子邮件

mysql - 如何创建一个 SQL 调用,以递归方式将 DISTINCT id 和父 id 合并到一个列中?

c++ - 给定 200 个字符串,什么是键控关系值 LUT 的好方法

c - 如何用c语言运行一个可执行文件?

c - 段错误和 argv、argc

c# - 在 C# 中表示此查找表的最佳方式