为了账号安全,请及时绑定邮箱和手机立即绑定

C++中的qsort问题

C++中的qsort问题

C++
静以修身淡以明志 2015-11-26 01:18:18
#include <stdio.h>#include <stdlib.h>struct c{    int x;    int y;    int ord;}d[100];int cmp(const struct c *a, const struct c *b){    if ((*a).x == (*b).x)        return (*a).y - (*b).y;    else        return (*a).x - (*b).x;}int main(void){    int i, j, n, max;    while (scanf("%d", &n), n)    {        for (max = i = 0; i < n; i++)        {            scanf("%d%d", &d[i].x, &d[i].y);            d[i].ord = 1;        }        qsort(d, n, sizeof(struct c), cmp);        d[n-1].ord = 1;        for (i = n - 2; i >= 0; i--)        {for (j = i + 1; j < n; j++)            {                if (d[i].y <= d[j].x && d[i].ord < d[j].ord + 1)                    d[i].ord = d[j].ord + 1;            }            if (max < d[i].ord)                max = d[i].ord;        }        printf("%d\n", max);    }    return 0;}这段程序在VC6下无法通过编译,是CMP函数的参数问题我改成cmp(void *a,void *b)这种形式也不行也通不过,提示函数参数不匹配error C2664: 'qsort' : cannot convert parameter 4 from 'int (const struct c *,const struct c *)' to 'int (__cdecl *)(const void *,const void *)'该怎样修改呢?
查看完整描述

1 回答

已采纳
?
DoDream

TA贡献28条经验 获得超3个赞

因为你的参数设计有问题,应该按照要求设为const void *,然后在函数中再转换成对应的结构体指针。

int cmp(const void *a, const void *b)

{

const struct c* a1 = (struct c*)a;

const struct c* b1 = (struct c*)b;

if ((*a1).x == (*b1).x)

return (*a1).y - (*b1).y;

else

return (*a1).x - (*b1).x;

}

我将你的cmp函数改了一下,编译通过了,你试试看行不行。

查看完整回答
反对 回复 2015-11-26
  • 1 回答
  • 0 关注
  • 1983 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信