17

给定一个结构数组(在 C 中),我试图按性别分组并按数字顺序按子顺序打印结果。例如:

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

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

struct employee info[2]={{"male","Matt",1234},{"female","Jessica",2345},{"male","Josh",1235}};

我怎么能去打印像这样的结果

1234 Matt
1235 Josh


2345 Jessica
4

3 回答 3

27

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

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 */
}

然后使用标准库中的 qsort 。

qsort(data, count, sizeof(struct employee), compare);

在 compare 函数中,您可能想要检查 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);
    }

带输出:

$ ./a.exe
1234    male    Matt
2345    female  Jessica
1235    male    Josh
1234    male    Matt
1235    male    Josh
2345    female  Jessica
于 2012-11-14T03:52:36.903 回答
2

在 struct 数组上使用您最喜欢的排序算法。在比较数组的两个元素以决定哪个“更大”时,比较它们的性别;如果性别相同,请比较他们的数字。(您可能希望定义一个单独的函数来进行此比较,以使事情更清楚。)然后,使用所需的格式按顺序打印排序的数组。跟踪性别何时从男性变为女性,以便您可以添加额外的三个换行符,如您的示例中所示。

编辑:为了无耻地从 kallikak 借用,您可以将比较函数传递给 qsort,但如果一个结构“更大”,则返回 1,如果“更少”则返回 -1,如果相同则返回 0(如有必要) (使用我上面概述的程序)。看看How to write a compare function for qsort from stdlib? 获取有关编写自定义比较函数的帮助。

于 2012-11-14T03:50:38.897 回答
1

认为它更容易理解,因为我的指针很弱

#include<bits/stdc++.h>

using namespace std;


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

bool compare(employee s1,employee s2)
{
  return s1.id<s2.id;
}

main()
{
  int i;
  struct employee info[]={{"male","Matt",1234},{"female","Jessica",2345},{"male","Josh",1235}};
  sort(info,info+3,compare);
  for (i = 0; i < 3; i++)
  printf("%d\t%s\t%s\n",info[i].id,info[i].gender,info[i].name);
}
于 2017-09-26T18:16:18.190 回答