简体   繁体   English

如何使用C语言对结构中的字符名称进行排序

[英]how To sort char name in a struct using C Language

how can you sort char firstName in a function and the names are read in from a text file already and external libraries can be used as well All students names are provided in a text file, which is read into an array of student records 如何在函数中对char firstName进行排序,并且已经从文本文件中读取名称,并且可以使用外部库所有学生名称都在文本文件中提供,该文件被读入学生记录数组中

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

The qsort function is typically used in C to sort an array. qsort函数通常在C中用于对数组进行排序。 One of the parameters is a pointer to a comparison function. 其中一个参数是指向比较函数的指针。 Write the function so that it compares the two pointers in any fashion you want. 编写函数,以便以任何方式比较两个指针。 You can even have different comparison functions so that you have the choice at run-time which will be applied. 您甚至可以使用不同的比较功能,以便在运行时选择将应用的功能。

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

The easy way, assuming you're not allowed to use external libraries, is with bubblesort. 假设您不允许使用外部库,那么简单的方法就是使用bubblesort。 Write a function that determines if an array of struct student s is already sorted. 编写一个函数来确定struct student的数组是否已经排序。 Then write a function that walk through such an array, comparing adjacent pairs of students. 然后编写一个遍历这样一个数组的函数,比较相邻的学生对。 If they're out of order, swap them. 如果它们出现故障,请更换它们。 Use the first function's result as the conditional clause of a while loop and the second function as the body. 使用第一个函数的结果作为while循环的条件子句,将第二个函数作为正文。

If you are allowed to use it, then qsort() from stdlib.h is by far the best approach. 如果你被允许使用它,那么stdlib.h qsort()是迄今为止最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM