本文主要是介绍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;
}
这篇关于qsort()中cmp函数写法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!