C++ qsort 使用陷阱

我相信使用STL提供的排序接口比自己实现排序算法更高效,也更具有通用性,能节省代码,而且对所有种类的数据的排序函数都是qsort,也提高了代码的可读性。在今天的工作中,qsort却把我折腾了一番,我犯了个小错误,在程序设计领域,小错误可以导致大后果,事后写了针对qsort的测试程序,如下:

 

 

qsortTest.cpp

1 #include <stdlib.h>
2 #include <string.h>
3 #include <stdio.h>
4
5 #include <iostream>
6  using namespace std;
7
8  int compare( const void *arg1, const void *arg2 );
9
10  int main()
11 {
12 int arrTest[] = {2,3,7,6,9,1,4,2,5,6,5,10,20,3,34};
13 int nCount = sizeof(arrTest)/sizeof(int);
14
15 cout << "before sort:" ;
16 for(int i=0;i<nCount;i++)
17 cout << arrTest[i] << " " ;
18 cout << endl;
19
20 qsort(arrTest,sizeof(arrTest)/sizeof(int),sizeof(int),compare);
21
22 cout << "after sort:" ;
23 for(int i=0;i<nCount;i++)
24 cout << arrTest[i] << " " ;
25 cout << endl;
26 return 0;
27 }
28  int compare( const void *arg1, const void *arg2 )
29 {
30 int * n1 = (int*)arg1;
31 int * n2 = (int*)arg2;
32 return *n1 > *n2;
33 }
34
35
36  

输出结果截图:

很明显,输出的结果排序错误。这个简单的程序,很快就可以定位错误在compare函数上,今天在工作中调试却并非如此简单,需要排序的是个结构体,排序前后还有数百行代码,当时调试了一个多小时之后才将错误定位到compare上面。

仔细查看MSDN,发现qsort函数需要的compare函数要返回三个值:负值,0,正值。

赶紧:将compare函数修正如下:

 

1 int compare( const void *arg1, const void *arg2 )
2 {
3 int * n1 = (int*)arg1;
4 int * n2 = (int*)arg2;
5 return *n1 - *n2;
6 }

 

 

 

查看输出,问题解决了,

 

仔细想想,用减法操作结果作为返回值只能适合整型比较,如果是浮点型的话,还是有问题的:返回值是整型,如果两个数大小是0.5,则compare函数会得到0.

 

以后用标准库函数,一定要仔细阅读MSDN!

 

posted @ 2010-03-12 16:08  stuarts  Views(1107)  Comments(2Edit  收藏  举报