qsort与功能比较器不同

时间:2019-04-13 03:18:42

标签: c qsort

我需要有关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);

1 个答案:

答案 0 :(得分:3)

假设(从您对qsort()的调用中),G->orden指向长度为u32的类型为G->n的值数组的底,然后将这些值传递给您的比较函数将是指向该数组元素的指针。您的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。我需要比较接收三个参数const void a const void b Grafo G。

在这种情况下,qsort()可能不适合您。还有qsort_r()qsort_b()qsort_r()需要一个附加的void*参数,该参数也已传递到比较函数中,听起来似乎最接近您的需要-您可以在此参数中传递指向G的指针。 qsort_b()采用比较块(也称为闭包)而不是函数,并且该块可以捕获调用者的上下文。

相关问题