【问题标题】:how To sort char name in a struct using C Language如何使用 C 语言对结构中的字符名称进行排序
【发布时间】:2010-11-24 22:09:15
【问题描述】:

如何在函数中对 char firstName 进行排序,并且名称已经从文本文件中读取,并且也可以使用外部库 所有学生的姓名都在一个文本文件中提供,该文件被读入学生记录数组

struct student{
   char*lastName; /*name of the student*/
   char*firstName;
   int age;       /*age of the student*/
   float grade[3];
}

【问题讨论】:

  • 您可以通过选择代码并按 CTRL+K 来格式化代码。使用预览。
  • 另外,您的问题没有提供足够的信息。你有什么样的数组/集合?这个结构没有告诉我们任何事情。

标签: c sorting


【解决方案1】:

qsort 函数通常在 C 中用于对数组进行排序。其中一个参数是指向比较函数的指针。编写函数,以便它以您想要的任何方式比较两个指针。您甚至可以使用不同的比较函数,以便在运行时选择要应用的函数。

int StudentCompare(const void * elem1, const void * elem2)
{
    const struct student * left = (const struct student *) elem1;
    const struct student * right = (const struct student *) elem2;
    int result;
    result = strcmp(left.firstName, right.firstName);
    if (result == 0)
        result = strcmp(left.lastName, right.lastName);
    return result;
}

【讨论】:

  • 参考 qsort(3) 手册页,您会看到 StudentCompare() 是“比较”参数。如果你有 struct student students[100];,那么你会调用 qsort(students, 100, sizeof(struct student), StudentCompare);
  • 另外,我认为在 StudentCompare() 实现中应该是 'struct student' 而不仅仅是 'student'。
  • @Wade,谢谢。我被 C++ 宠坏了太久了。已编辑。
【解决方案2】:

假设您不允许使用外部库,最简单的方法是使用冒泡排序。编写一个函数来确定struct students 的数组是否已经排序。然后编写一个遍历这样一个数组的函数,比较相邻的学生对。如果它们不正常,请交换它们。将第一个函数的结果用作 while 循环的条件子句,将第二个函数的结果用作主体。

如果您被允许使用它,那么stdlib.h 中的qsort() 是迄今为止最好的方法。

【讨论】:

  • 插入排序通常更简单,更快。另外,qsort() 不是外部库,而是包含在 C 标准库中。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2016-03-11
  • 2020-08-09
  • 2021-07-30
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 2021-04-28
相关资源
最近更新 更多