qsort()中cmp函数写法

函数原型:
void qsort(
void *base,
size_t num,
size_t width,
int (__cdecl *compare )(const void *, const void *)
);


参数:
base:Start of target array.
num:Array size in elements.
width:Element size in bytes.
compare:Pointer to a user-supplied routine that compares two array elements and returns a value that specifies their relationship.


这里的compare( (void *) & elem1, (void *) & elem2 )需要自己编写也正是STL库函数灵活的一个特点。有了这个,可以很轻松的对字符串数组,二维字符串数组进行字典排序,可以对结构体按照关键字进行一级排序,也可以为了使其稳定的二级或者多级排序。
Compare function return value Description
< 0 elem1 less than elem2
0 elem1 equivalent to elem2
> 0 elem1 greater than elem2
*The array is sorted in increasing order, as defined by the comparison function. To sort an array in decreasing order, reverse the sense of “greater than” and “less than” in the comparison function.


对int型数组进行排序(char和double同int):
int cmp (const void *a , const void *b){
return *(int *)a - *(int *)b;
}
对结构体排序:
int cmp (const void *a , const void *b){
return (*(Node*)a)->x - (*(Node*)b)->x;
}
struct Node{
int x;
int y;
}
对字符串排序:
int cmp(const void *a, const void *b){
return strcmp((char *)a,(char *)b);
}//按照字典序递增的顺序排序


计算几何中求凸包的cmp
int cmp(const void *a,const void *b) //重点cmp函数,把除了1点外的所有点,旋转角度排序
{
struct point *c=(point *)a;
struct point *d=(point *)b;
if( calc(*c,*d,p[1]) < 0) return 1;
else if( !calc(*c,*d,p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y)) //如果在一条直线上,则把远的放在前面
return 1;
else return -1;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值