简体   繁体   English

cpp中指针的类型转换

[英]typecasting of pointers in cpp

Can anybody tell me what's going on with the following code:谁能告诉我下面的代码发生了什么:

int compareX(const void* a, const void* b)  
 {  
    Point *p1 = (Point *)a, *p2 = (Point *)b;  
    return (p1->x - p2->x);  
 }

I have taken this code from geeks for geeks, the closest pair of points .我从 geeks for geeks 那里获取了这段代码,最近的点对 can anyone explain to me the similar code in a much simpler and easy way with line by line explanation任何人都可以通过逐行解释以更简单和容易的方式向我解释类似的代码

also, I am unable to understand this piece of code as well:另外,我也无法理解这段代码:

float bruteForce(Point P[], int n)  
{  
    float min = FLT_MAX;
    for (int i = 0; i < n; ++i)  
        for (int j = i+1; j < n; ++j)  
            if (dist(P[i], P[j]) < min)  
                min = dist(P[i], P[j]);  
    return min;  
}  

What's the use of FLT_MAX here?这里的FLT_MAX什么用?

Point *p1 = (Point *)a, *p2 = (Point *)b;

This line is initialising two variables in the same line.这一行正在初始化同一行中的两个变量。 Like喜欢

int a = 2, b = 3;

For pointers, the * is kept near the variable.对于指针, *保持在变量附近。 The following will give you an int * and an int :以下将为您提供一个int *和一个int

 int *a = nullptr, b = 2;

https://cdecl.org https://cdecl.org


what's the use of FLT_MAX here?这里 FLT_MAX 有什么用?

Everything is smaller than FLT_MAX .一切都小于FLT_MAX So this is safe to check against in the first comparison for the minimum number.因此,在第一次比较最小数量时可以安全地进行检查。

FLT_MAX这里定义的常量,如果用于查找数组中所有点对之间距离最小的点的逻辑,使用 FLT_MAX 设置变量 min 的想法是定义可以超过的阈值限制值通过第一次 2 点的第一次比较...

The compareX function in your first code snippet has the signature required if it is to be passed as the comparator in a call to the standard qsort() function (or other, similar sorting routines provided by the Standard Library).如果要在调用标准qsort()函数(或标准库提供的其他类似排序例程qsort()将它作为比较器传递,则第一个代码片段中的compareX函数具有所需的签名。 The two pointer arguments must be given as const void* types.两个指针参数必须作为const void*类型给出。

However, when that function is used, the code will actually be passing pointers to Point objects, so the function must first explicitly cast them as such, so that they can be dereferenced in order to do the comparison of their respective x members.但是,当使用该函数时,代码实际上将传递指向Point对象的指针,因此该函数必须首先显式地将它们转换为这样,以便可以取消引用它们,以便对它们各自的x成员进行比较。

Note: Although using "C-Style" casts will work here, many would frown on such usage.注意:虽然在这里使用“C-Style”强制转换可以工作,但许多人会不赞成这种用法。 It is, perhaps, more in keeping with "Modern C++" to use static_cast operations:使用static_cast操作也许更符合“现代 C++”:

int compareX(const void* a, const void* b)
{
    const Point *p1 = static_cast<const Point*>(a), *p2 = static_cast<const Point*>(b);
    return (p1->x - p2->x);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM