如何从 stdlib 为 qsort 编写比较函数? [英] How to write a compare function for qsort from stdlib?

查看:15
本文介绍了如何从 stdlib 为 qsort 编写比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构:

struct pkt_
{
  double x;
  double y;
  double alfa;
  double r_kw;
};

typedef struct pkt_ pkt;

这些结构的表格:

pkt *tab_pkt;

tab_pkt = malloc(ilosc_pkt * sizeof(pkt));

我要做的是通过 tab_pkt.alfatab_pkt.rtab_pkt 进行排序:

What I want to do is to sort tab_pkt by tab_pkt.alfa and tab_pkt.r:

qsort(tab_pkt, ilosc_pkt, sizeof(pkt), porownaj);

porownaj 是一个比较函数,但是怎么写呢?这是我的草图":

Where porownaj is a compare function, but how to write it? Here is my "sketch" of it:

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 < pkt_b.alfa && pkt_a.r_kw < pkt_b.r_kw) return -1;
}

推荐答案

这样的东西应该可以工作:

Something like this should work:

int porownaj(const void *p_a, const void *p_b)
{
  /* Need to store arguments in appropriate type before using */
  const pkt *pkt_a = p_a;
  const pkt *pkt_b = p_b;

  /* Return 1 or -1 if alfa members are not equal */
  if (pkt_a->alfa > pkt_b->alfa) return 1;
  if (pkt_a->alfa < pkt_b->alfa) return -1;

  /* If alfa members are equal return 1 or -1 if r_kw members not equal */
  if (pkt_a->r_kw > pkt_b->r_kw) return 1;
  if (pkt_a->r_kw < pkt_b->r_kw) return -1;

  /* Return 0 if both members are equal in both structures */
  return 0;
}

远离愚蠢的把戏,比如:

Stay away from silly tricks like:

return pkt_a->r_kw - pkt_b->r_kw;

它返回非规范化的值,难以阅读,无法正常处理浮点数,有时甚至会出现棘手的极端情况,即使是整数值也无法正常工作.

which return un-normalized values, are confusing to read, won't work properly for floating point numbers, and sometimes have tricky corner cases that don't work properly even for integer values.

这篇关于如何从 stdlib 为 qsort 编写比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆