繁体   English   中英

如何在C编程中使用qsort对Struct进行排序

[英]How to sort Struct using qsort in C programming

我创建了一个结构数组,我想使用qsort对它们进行排序,以便按时间顺序将日期排序为字符串month,或者我应该说char month []。 我如何使以下代码根据一个月显示该结构。 请指教。 谢谢

struct dates
{
    int index;
    int day;
    int year;
    char month[15];
};


int i=0;
int count = 0 ;
char test ='\0';
int total =0;

printf("Please enter the number of dates you need to display");
scanf("%d",&total);
struct dates *ip[total];

for(count =0; count< total; count++){
    ip[count] = (struct dates*)malloc(sizeof(struct dates));

    printf("\nEnter the name month.");
    scanf("%s", ip[count]->month);

    printf("\nEnter the Day.");
    scanf("%d",&ip[count]->day);

    printf("\nEnter the Year.");
    scanf("%d", &ip[count]->year);                      
}

for(i=0; i<total; i++){
    printf("%s %d %d\n\n",ip[i]->month,ip[i]->day,ip[i]->year);
}

您可以定义自己的比较器来对http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/进行排序

所以要对整数进行排序

int intcomp(void *a, void *b){
  int *_a = (int *)a;
  int *_b = (int *)b;

  if(*_a > *_b) return -1;
  if(*_a == *_b) return 0;
  return 1;
}

我认为您可以从中创建自己的比较器功能。

qsort的手册页中有一个示例

static int
cmp(const void *p1, const void *p2)
{
        int y1 = ((const struct dates*)p1)->year;
        int y2 = ((const struct dates*)p2)->year;

        if (y1 < y2)
            return -1;
        else if (y1 > y2)
            return 1;

        /* years must be equal, check months */
        ...
}

接着

qsort(dates, total, sizeof(*dates), cmp);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM