qsort:
前几天刷题的时候有一题因为这个函数的原因,WA了无数次
我现在对这个函数的理解是:
对于要排序的一个数组中的两个元素 a,b,
1、 当cmp返回1的时候,sort的操作就把a放在后面;
2、当cmp返回-1的时候,sort的操作就把a放在前面;
3、当cmp返回0的时候,sort的操作不做任何改变。
比方说 要按升序排列的话 当a〉b的时候返回1 当 a 〈b的时候返回-1
手册上的解释:
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:
| |
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 value | meaning |
---|---|
<0 | The element pointed by p1 goes before the element pointed by p2 |
0 | The element pointed by p1 is equivalent to the element pointed by p2 |
>0 | The element pointed by p1 goes after the element pointed by p2 |
For types that can be compared using regular relational operators, a general compar function may look like:
| |
sort:
cmp函数:
-
Binary function that accepts two elements in the range as arguments, and returns a value convertible to
bool
. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.