我想使用 qsort() 对数组 a 相对于 b 进行排序。能给我这个函数吗?
a={0,1,2,3,4} b={3,4,5,1,2}
答案必须是 {3,4,0,1,2}
请给我函数代码。
如:
int 比较 (const void *a,const void *b)
{
返回(*(char *)a-*(char *)b);
}
最佳答案
这在您目前的方式中是不可能的,因为 qsort() 接受一个数组并将数组的元素相互比较。您需要创建包含两个值的结构的单个数组,如下所示:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int a;
int b;
} c_type;
int
compare(const void *a,
const void *b) {
return ((c_type *)a)->b - ((c_type *)b)->b;
}
int
main(int argc,
char *argv[])
{
int i = 0;
c_type array[] = {{0, 3}, {1, 4}, {2, 5}, {3, 1}, {4, 2}};
qsort(array, sizeof array / sizeof(*array), sizeof(*array), compare);
for ( i = 0; i < sizeof array / sizeof(*array); i++ ) {
printf("%d\t", array[i].a);
}
printf("\n");
return 0;
}
关于c - 一个数组相对于另一个数组的 qsort(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523995/