排序结构数组的成员

bar*_*kyo 13 c arrays sorting structure

给定一个结构数组(在C中)我试图以数字顺序打印出性别组和子顺序的结果.例如:

struct employee{
char gender[13]
char name[13];
int id;
};
Run Code Online (Sandbox Code Playgroud)

假设我像这样定义结构数组:

struct employee info[2]={{"male","Matt",1234},{"female","Jessica",2345},{"male","Josh",1235}};
Run Code Online (Sandbox Code Playgroud)

我怎么能打印结果像

1234 Matt
1235 Josh


2345 Jessica
Run Code Online (Sandbox Code Playgroud)

kal*_*kak 20

您需要实现一个排序函数,根据需要比较结构

int compare(const void *s1, const void *s2)
{
  struct employee *e1 = (struct employee *)s1;
  struct employee *e2 = (struct employee *)s2;
  int gendercompare = strcmp(e1->gender, e2->gender);
  if (gendercompare == 0)  /* same gender so sort by id */
    return e1->id - e2->id;
  else
    return -gendercompare;  /* the minus puts "male" first as in the question */
}
Run Code Online (Sandbox Code Playgroud)

然后使用标准库中的qsort.

qsort(data, count, sizeof(struct employee), compare);
Run Code Online (Sandbox Code Playgroud)

在比较函数内部,您可能需要检查id是否相等,然后您可以按名称排序(也可以使用strcmp()),但是您喜欢.

编辑:刚刚编译并修复了这个问题.这是一个小测试程序

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

    struct employee{
      char gender[13];
      char name[13];
      int id;
    };

    int compare(const void *s1, const void *s2)
    {
      struct employee *e1 = (struct employee *)s1;
      struct employee *e2 = (struct employee *)s2;
      int gendercompare = strcmp(e1->gender, e2->gender);
      if (gendercompare == 0)  /* same gender so sort by id */
        return e1->id - e2->id;
      else
        return -gendercompare;
    }

    main()
    {
      int i;
      struct employee info[]={{"male","Matt",1234},{"female","Jessica",2345},{"male","Josh",1235}};

      for (i = 0; i < 3; ++i)
        printf("%d\t%s\t%s\n", info[i].id, info[i].gender, info[i].name);

      qsort(info, 3, sizeof(struct employee), compare);

      for (i = 0; i < 3; ++i)
        printf("%d\t%s\t%s\n", info[i].id, info[i].gender, info[i].name);
    }
Run Code Online (Sandbox Code Playgroud)

随着输出:

$ ./a.exe
1234    male    Matt
2345    female  Jessica
1235    male    Josh
1234    male    Matt
1235    male    Josh
2345    female  Jessica
Run Code Online (Sandbox Code Playgroud)