qsort的使用

来源:互联网 发布:淘宝包裹放微信二维码 编辑:程序博客网 时间:2024/05/16 09:00

原地址

CPlusPlus


function
<cstdlib>

qsort

void qsort (void* base, size_t num, size_t size,            int (*compar)(const void*,const void*));
Sort elements of array
Sorts the num elements of the array pointed to by base, each element size bytes long, using the compar function to determine the order.
对由指针base指向的array数组的num个元素排序,每个元素的大小是size byte使用compar函数来决定顺序。
compar
Pointer to a function that compares two elements.
This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:
 
int compar (const void* p1, const void* p2);
 

Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):
return valuemeaning<0The element pointed to by p1 goes before the element pointed to by p20The element pointed to by p1 is equivalent to the element pointed to by p2>0The element pointed to by p1 goes after the element pointed to by p2
For types that can be compared using regular relational operators, a general compar function may look like:

123456
int compareMyType (const void * a, const void * b){  if ( *(MyType*)a <  *(MyType*)b ) return -1;  if ( *(MyType*)a == *(MyType*)b ) return 0;  if ( *(MyType*)a >  *(MyType*)b ) return 1;}
 


总结:

qsort第一个参数是指向基地址的指针,第二个参数是要排序的元素的个数,第三个参数是被排序的每个元素的大小,第四个参数是cmp函数,这个函数用来决定排序的顺序
关于cmp函数:由上面的例子可知,如果返回值大于0,a会被移到b的后面。如果小于0,a在b前。可以理解成默认是按降序。具体写法要参照具体情况。
一个例子:(整数数组arr按照升序排列)

int compareMyType (const void * a, const void * b){  if ( *(int*)a >  *(int*)b ) return -1;  if ( *(int*)a == *(int*)b ) return 0;  if ( *(int*)a <  *(int*)b ) return 1;}




0 0
原创粉丝点击