我是C语言的初学者, 我正在尝试理解qsort函数所需的比较函数。
第一部分: 语法
一个简单的建议用法是这样的(我已经包含了一些main()代码来打印结果):
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25, 12, 13, 10, 40 };
int compare(const void *a, const void *b)
{
const int *ia = (const int *)a; // casting pointer types
const int *ib = (const int *)b;
return *ia - *ib;
}
int main()
{
int n;
for (n=0; n<10; n++)
{
printf("%d ",values[n]);
}
printf("\n");
qsort(values, 10, sizeof(int), compare);
for (n=0; n<10; n++)
{
printf("%d ",values[n]);
}
printf("\n");
system("pause");
return 0;
}
我不明白为什么你需要在比较函数中加入所有的额外内容,所以我将它简化成这样:
int compare (int *a, int *b)
{
return *a-*b;
}
这仍然可用,并产生相同的结果。有人能否解释一下我删除了什么,以及为什么它仍然有效?
第二部分:为什么要使用指针?
另外,我真的需要使用指针吗?为什么不能像这样直接比较“a”和“b”(这是行不通的):
int compare (int a, int b)
{
return a-b;
}
出于某种原因,对于多维数组,我竟然可以不使用指针就成功了!这是怎么回事呢?(以下是按每个子数组中第二项对多维数组进行排序的示例代码):
#include <stdio.h>
#include <stdlib.h>
int values[7][3] = { {40,55}, {10,52}, {100,8}, {90,90}, {20,91}, {25,24} };
int compare(int a[2], int b[2])
{
return a[1] - b[1];
}
int main()
{
int n;
for (n=0; n<6; n++)
{
printf("%d,",values[n][0]);
printf("%d ",values[n][1]);
}
printf("\n");
qsort(values, 6, sizeof(int)*3, compare);
for (n=0; n<6; n++)
{
printf("%d,",values[n][0]);
printf("%d ",values[n][1]);
}
printf("\n");
system("pause");
return 0;
}
我真的很高兴多维数组排序正在工作,因为那是我的最终目标,但我不知道我如何使它工作(除了运气和剪辑代码之外),所以我真的希望能对我提供的一些示例为什么有些有效而有些无效进行解释!
const void*
。将该指针转换为const int*
。然后像通常一样使用operator[]
。 - Billy ONeal