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函数来决定顺序。
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):
<0
The element pointed to by p1 goes before the element pointed to by p20
The element pointed to by p1 is equivalent to the element pointed to by p2>0
The element pointed to by p1 goes after the element pointed to by p2For 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
- qsort的使用
- STL的qsort使用
- qsort的使用
- qsort的使用
- qsort的使用
- qsort的使用
- qsort 函数的使用
- qsort的使用小结
- qsort的使用
- qsort的使用
- qsort的使用
- qsort的使用
- qsort的使用
- qsort函数的使用
- 关于qsort的使用
- qsort的使用
- qsort的使用方式
- 关于qsort的使用【转】
- sublime3 docblocker插件定制自己的注释,配置步骤
- 基础概念3
- 方法(函数)
- LeetCode进阶之路(Spiral Matrix)
- 漫谈OC
- qsort的使用
- Spark 的运行流程原理
- OpenStack Mitaka keystone 分页(pagination)实现
- 深度优先遍历和广度优先遍历
- redis性能评测
- ios常用的宏定义
- 算法导论-最小生成树之kruskal算法和prim算法
- 线程安全和线程不安全理解
- hdu 2844 Coins(多重背包)