作者:旭峰fd_817 | 来源:互联网 | 2023-09-08 12:30
I have a structure:
我有一个结构:
struct pkt_
{
double x;
double y;
double alfa;
double r_kw;
};
typedef struct pkt_ pkt;
A table of these structures:
这些结构的表格:
pkt *tab_pkt;
tab_pkt = malloc(ilosc_pkt * sizeof(pkt));
What I want to do is to sort tab_pkt
by tab_pkt.alfa
and tab_pkt.r
:
我想要做的是通过tab_pkt.alfa和tab_pkt.r对tab_pkt进行排序:
qsort(tab_pkt, ilosc_pkt, sizeof(pkt), porownaj);
Where porownaj is a compare function, but how to write it? Here is my "sketch" of it:
porownaj是比较函数,但如何写呢?这是我的“草图”:
int porownaj(const void *pkt_a, const void *pkt_b)
{
if (pkt_a.alfa > pkt_b.alfa && pkt_a.r_kw > pkt_b.r_kw) return 1;
if (pkt_a.alfa == pkt_b.alfa && pkt_a.r_kw == pkt_b.r_kw) return 0;
if (pkt_a.alfa
3 个解决方案
1
There are two parts to the problem - how to write the code, and how to compare the packet types. You must ensure you always return a value. Your code should also always be such that:
该问题分为两部分 - 如何编写代码,以及如何比较数据包类型。您必须确保始终返回值。您的代码也应始终如此:
porownaj(&pkt_a, &pkt_b) == -porownaj(&pkt_b, &pkt_a)
Your outline comparison does not handle cases such as:
您的大纲比较不处理以下情况:
pkt_a->alfa > pkt_b->alfa && pkt_a->r_kw <= pkt_b->r_kw
pkt_a->alfa alfa && pkt_a->r_kw >= pkt_b->r_kw
pkt_a->alfa == pkt_b->alfa && pkt_a->r_kw != pkt_b->r_kw
There is one more problem - is it appropriate to compare floating point values for exact equality? That will depend on your application.
还有一个问题 - 比较浮点值是否适合精确相等?这取决于您的申请。
Mechanically, you have to convert the const void pointers to const structure pointers. I use the explicit cast - C++ requires it, and I try to make my code acceptable to a C++ compiler even when it is really C code.
在机械上,您必须将const void指针转换为const结构指针。我使用显式强制转换--C ++需要它,我尝试使我的代码可以接受C ++编译器,即使它真的是C代码。
int porownaj(const void *vp1, const void *vp2)
{
const pkt *pkt_a = (const pkt *)vp1;
const pkt *pkt_b = (const pkt *)vp2;
if (pkt_a->alfa > pkt_b->alfa && pkt_a->r_kw > pkt_b->r_kw) return 1;
if (pkt_a->alfa == pkt_b->alfa && pkt_a->r_kw == pkt_b->r_kw) return 0;
if (pkt_a->alfa alfa && pkt_a->r_kw r_kw) return -1;
return 0;
}
This does not deal with the bits that I cannot resolve since I am not party to the necessary information. Note that, in general, multi-dimensional objects (such as complex numbers, or (x,y) or (x,y,z) coordinates) cannot simply be compared for greater than or less than or equal to.
这不涉及我无法解决的比特,因为我不是必要信息的参与者。注意,通常,多维对象(例如复数,或(x,y)或(x,y,z)坐标)不能简单地比较大于或小于或等于。