qsort排序失败

狂日一条街 2012-05-26 04:26:50
这是我的代码这是我的测试结果各位大神求解释为什么会排序失败按道理来说不是升序就是降序偏偏这么奇葩
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int comp(const void *a,const void *b)
{
int c;
return c=((string *)a<=(string *)b?1:-1);
}
int main()
{
int a[7];
for(int x=0;x<7;x++)
cin>>a[x];
qsort(a,7,sizeof(int),comp);
qsort(a,7,sizeof(int),comp);

for(int x=0;x<7;x++)
cout<<a[x]<<" ";
return 0;

}
输入:7 6 5 4 3 2 1

输出:5 4 3 2 1 7 6 请按任意键继续. . .
...全文
200 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
tongzhipeng5699 2012-05-27
  • 打赏
  • 举报
回复
++

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int comp(const void *a,const void *b)
{
return *((int*)a)>=*((int*)b);
}
int main()
{
int a[7];
for(int x=0;x<7;x++)
cin>>a[x];
qsort(a,7,sizeof(int),comp);
qsort(a,7,sizeof(int),comp);

for(int x=0;x<7;x++)
cout<<a[x]<<" ";
return 0;

}



[Quote=引用 1 楼 的回复:]
return c=((string *)a<=(string *)b?1:-1); ????转换成int吧
[/Quote]
qq120848369 2012-05-27
  • 打赏
  • 举报
回复
       For one example of use, see the example under bsearch(3).

Another example is the following program, which sorts the strings given in its command-line arguments:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int
cmpstringp(const void *p1, const void *p2)
{
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp(3) arguments are "pointers
to char", hence the following cast plus dereference */

return strcmp(* (char * const *) p1, * (char * const *) p2);
}

int
main(int argc, char *argv[])
{
int j;

if (argc < 2) {
fprintf(stderr, "Usage: %s <string>...\n", argv[0]);
exit(EXIT_FAILURE);
}

qsort(&argv[1], argc - 1, sizeof(char *), cmpstringp);

for (j = 1; j < argc; j++)
puts(argv[j]);
exit(EXIT_SUCCESS);
}



这是个例子,楼主在==的时候应该返回0,但你没有。
qq120848369 2012-05-27
  • 打赏
  • 举报
回复
请使用<,而不是<=或者>=。

qsort的实现认为用户提供的是<号,而不是<=,如果你提供的不一致,必将导致排序结果混乱。
okili 2012-05-26
  • 打赏
  • 举报
回复
还是不行啊
ningto.com 2012-05-26
  • 打赏
  • 举报
回复
return c=((string *)a<=(string *)b?1:-1); ????转换成int吧

65,207

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧