STL中qsort的一点疑问
本帖最后由 bhdp_hhhz1 于 2013-01-13 16:59:28 编辑
int doublecompare(const void* double1,const void* double2)
{
return *((double*)double2)- *((double*)double1);
}
int doublecompare2(const void* double1,const void* double2)
{
return *((double*)double2)> *((double*)double1);
}
double a[]={66,631,6,114,10,9,7,78,96};
qsort(a,9,sizeof(double),doublecompare);
用doublecompare是对的,用doublecompare2排序是
96 631 78 114 66 10 9 7 6
请问下,是什么原因造成了以上的结果
[解决办法]
qsort 对 compare function 有要求的
compar
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 * elem1, const void * elem2 );
Taking a pointer to two pointers as arguments (both type-casted to const void*). The function should compare the data pointed by both: if they match in ranking, the function shall return zero; if elem1 goes before elem2, it shall return a negative value; and if it goes after, a positive value.
doublecompare2 只能返回 0 或 1,无法返回负值,不符合要求.
[解决办法]
不能这样的比较浮点数。详细见:《使用VC库函数中的快速排序函数》
http://blog.csdn.net/morewindows/article/details/6684561