我正在尝试重构一个当前是独立 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/