gpt4 book ai didi

c++ - 使用 qsort 对 2D 数组进行排序 - 正确的类型转换

转载 作者:行者123 更新时间:2023-11-30 17:10:08 24 4
gpt4 key购买 nike

我在使用 C++ qsort 比较函数正确按字典顺序对二维整数数组进行排序时遇到问题。我已经在这里读过很多类似的问题,但没有成功。在制作自定义比较函数时,其参数的形式为

int compar (const void* p1, const void* p2)

现在,我知道参数是指向我的变量的指针,每个变量都指向我的数组的一行。我想使用如下所示的方式以正常的传统方式索引和比较我的数组。

if(p1[0] <= p2[0]) {...}

因为我知道,格式

p1[i]

只是指针算术的快捷方式,我想当我收到参数“指向 int 指针的指针”时,我应该进行类型转换并以这种方式使用它:

if(*(int**)p1[0] <= *(int**)p2[0]) {...}

编译器给了我很多这样的错误

main.cpp:8:20: error: ‘const void*’ is not a pointer-to-object type
main.cpp:8:37: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith]

我的问题是,如何正确地转换它,这样我就可以比较我的行。另外,我想了解,我在这里做错了什么,以避免将来犯这些与指针相关的错误。

最佳答案

这是因为 operator[] 优先于强制转换。 b[0] 正在尝试首先解决。因此,即使它是 b[0] 它也会提示您正在对 void* 类型进行指针算术。你需要施放第一。

#include <iostream>
using namespace std;

int main() {
int a[10];
a[0] = 1337;
a[1] = 42;
void* b;
b = (void*)a;

// cout << (int*)b[0] << '\n'; // will break
cout << ((int*)b)[0] << '\n';

// dedicated c++ cast imposes more verbose syntax - i.e. you can't miss the ()
cout << static_cast<int*>(b)[1] << '\n';
return 0;
}

话虽如此,我仍然鼓励您使用 C++ 专用功能来完成您正在做的事情 =)。

关于c++ - 使用 qsort 对 2D 数组进行排序 - 正确的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33011038/

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