首页 文章

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

提问于
浏览
0

我已经创建了一个struct数组,我想用qsort对它们进行排序,按时间顺序将日期排序到字符串月份,或者我应该说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);
}

2 回答

  • 3

    你可以定义自己的比较器来排序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;
    }
    

    我认为你可以自己制作比较器功能 .

  • 3

    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);
    

相关问题