我需要有关 qsort 中函数 COMPARE 的帮助。比较数组 G->orden,但与在另一个数组中用作索引的 order 元素进行比较,以及如何在中插入 G 进行比较。
struct VerticeSt {
u32 nombre;
u32 color;
u32 grado;
u32 *vecinos;
};
struct GrafoSt {
u32 n;
u32 m;
u32 nc;
u32 delta;
Vertices v;
u32 *orden;
};
int Compare(const void* a, const void* b) {
u32* x1 = (u32*) a;
u32* x2 = (u32*) b;
if(G->v[G->orden[x1]] < G->v[G->orden[x2]])
return -1;
else
.
.
.
}
qsort(G->orden, G->n, sizeof(u32), Compare);
假设(从你对qsort()
的调用)G->orden
指向长度为G->n
的u32
类型的值数组的基数,那么传递给比较函数的值将是指向该数组元素的指针。Compare()
函数应将传递给它的void*
指针强制转换为指向它知道的类型的指针,然后取消引用这些指针以获取它将比较的实际值。
这是一个简短的程序,展示了整个事情的实际效果:
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long u32;
int Compare(const void* a, const void* b) {
u32 x1 = *(u32*)a; // Get the array element that a points to
u32 x2 = *(u32*)b; // Get the array element that b points to
if (x1 < x2) // Compare the values and return result
return -1;
else if (x1 == x2)
return 0;
else return 1;
}
void printArray(char* label, u32* a, int n) {
printf("%s", label);
for (int i = 0; i < n; i++)
printf("t%lu", (unsigned long)a[i]);
printf("n");
}
int main(int argc, const char* argv[]) {
u32 array[5] = {9, 3, 27, 18, 6};
printArray("unsorted: ", array, 5);
qsort(array, 5, sizeof(u32), Compare);
printArray(" sorted: ", array, 5);
return 0;
}
结果如下:
unsorted: 9 3 27 18 6
sorted: 3 6 9 18 27
在 qsort 中比较接收两个参数 const void a , const void b。我需要比较接收三个参数 常量无效 a 常量空 b 格拉福 G.
在这种情况下,qsort()
可能不是适合您的功能。还有qsort_r()
和qsort_b()
.qsort_r()
采用一个额外的void*
参数,该参数也传递到比较函数中,这听起来最接近您需要的 - 您可以在此参数中传递指向G
的指针。qsort_b()
采用比较块(也称为闭包)而不是函数,并且该块可以从调用方捕获上下文。