排序结构数组的成员

时间:2012-11-14 03:42:06

标签: c arrays sorting structure

给定一个结构数组(在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

3 个答案:

答案 0 :(得分: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 */
}

然后使用标准库中的qsort。

qsort(data, count, sizeof(struct employee), 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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

认为它更容易理解,因为我指针很弱,希望它有帮助............

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