gpt4 book ai didi

c - qsort 无法正常使用 long long

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:44 26 4
gpt4 key购买 nike

我正在对二维数组 a[n][2] 进行排序,a[i][0]、a[i+1][0] 与非递减 a[i][1 ],[i+1][1]。qsort 适用于整数数组,但不适用于 long long 数组。

整数数组代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
int x = ((int*)a)[0] - ((int*)b)[0];
if (x != 0) {
return x;
}
return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
int n, i, j;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i = i + 1) {
scanf("%d %d", &a[i][0], &a[i][1]);
}
qsort(a, n, sizeof(a[0]), cmpfunc);
for (i = 0; i < n; i = i + 1) {
printf("%d %d\n", a[i][0], a[i][1]);
}
return 0;
}

长长数组代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
int x = ((int*)a)[0] - ((int*)b)[0];
if (x != 0) {
return x;
}
return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
int n, i, j;
scanf("%d", &n);
long long a[n][2];
for (i = 0; i < n; i = i + 1) {
scanf("%I64d %I64d", &a[i][0], &a[i][1]);
}
qsort(a, n, sizeof(a[0]), cmpfunc);
for (i = 0; i < n; i = i + 1) {
printf("%I64d %I64d\n", a[i][0], a[i][1]);
}
return 0;
}

输入:

5
4 3
4 2
4 1
4 1
4 1

第一个代码的输出:

4 1
4 1
4 1
4 2
4 3

第二个代码的输出:

4 2
4 1
4 1
4 1
4 3

最佳答案

您实际上有两个 问题:第一个是无效转换的问题。第二个是关于无效转换的也是,但出于另一个原因。

如我的评论之一所述,qsort 函数将指针指向元素 传递给比较函数。如果你有一个数组 arr 那么 qsort 将使用类似 &arr[0] 的参数。这意味着如果数组的数据本身就是数组,那么参数将是指向数组的指针。在您的特定情况下,参数类型实际上是 long long (*)[2],而不仅仅是 long long *

所以比较函数应该看起来像这样:

int cmpfunc(const void* a_, const void* b_)
{
long long (*a)[2] = (long long (*)[2]) a_;
long long (*b)[2] = (long long (*)[2]) b_;

long long result;

if ((*a)[0] - (*b)[0] != 0)
result = (*a)[0] - (*b)[0];
else
result = (*a)[1] - (*b)[1];

if (result < 0)
return -1;
else if (result > 0)
return 1;
else
return 0;
}

关于c - qsort 无法正常使用 long long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com