需要帮助将 qsort 与结构数组一起使用 [英] Need help using qsort with an array of structs

查看:45
本文介绍了需要帮助将 qsort 与结构数组一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我看过各种例子,但我不明白它们的意思.

Now, I have seen various examples, but I don't get what they mean.

这是我的结构

typedef struct profile{
    char gender[1];
    double soc;
       . . .
} PROFILE;

其中 soc 是我将要排序的社会安全号码.

where soc is social security number that I'm going to be sorting by.

我知道您需要一个比较函数,但我不知道如何得出我需要的确切内容.

I know you need a compare function, but I don't know how to come up with the exact thing I need.

推荐答案

这里是一个在 C 中使用 qsort 处理结构数组的例子

Here is an example of using qsort for an array of structs in C

/* qsort example */
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int price;
    int id;
} order;
order list[6];
int i = 0;

int compare (const void * a, const void * b)
{

  order *orderA = (order *)a;
  order *orderB = (order *)b;

  return ( orderB->price - orderA->price );
}

int main ()
{
    srand ( time(NULL) );

    printf("Before sorting\n");
    for(i=0; i<6; i++){ 
        list[i].price = rand()%10;
        list[i].id = i; 
        printf ("Order id = %d Price = %d \n",list[i].id, list[i].price);           
    }
    printf("AFTER sorting\n");
    int n;
    qsort (list, 6, sizeof(order), compare);
    for (n=0; n<6; n++)
         printf ("Order id = %d Price = %d \n",list[n].id, list[n].price);          
    return 0;
}

希望能帮到你

卡特琳娜·迪米特里斯

(所有关于pitsi)

(all regards to pitsi)

这篇关于需要帮助将 qsort 与结构数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆