如何对嵌套在结构数组中的结构数组进行排序 C [英] How to sort an array of structs nested in a array of structs C

查看:26
本文介绍了如何对嵌套在结构数组中的结构数组进行排序 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有与此类似的帖子,但我无法理解它们,所以我也在制作一个,所以请不要将其标记为重复:)

I know there are similiar posts to this one but I can't get my head around them so I'm making one too so please don't mark this as a duplicate :)

我有 2 个嵌套的结构数组,其中外部结构是比赛,内部结构是来自这些比赛的船只数量.我想对内部结构进行排序,以便船按 time_to_complete_race 的升序排列,一旦完成此操作,我将分配数组中的第一条船 points = 4,第二个points = 2 和第三个points = 1.不过我还没有实现积分分配,所以请忽略这部分.

I've got 2 nested arrays of structs where the outer structs are races and the inner structs are the number of boats from those races. I want to sort the inner struct so that the boats are in ascending order of time_to_complete_race and once I've done this I then assign the first boat in the array points = 4, the second points = 2 and the thirdpoints = 1. I haven't however implemented the points assinging yet so please ignore this part.

struct boat_data {
    int ID;
    int time_to_complete_race;
    int points;
} boat_node;
typedef struct race_result {
    char race_date[80];
    int start_time;
    int num_boats_competing;
    struct boat_data boat_data[MAX_BOAT_NUMBER];
} race_node;

这是我用来对内部结构进行排序的代码:

Here is the code that I am using to sort the inner stucts:

void print_races(int races, race_ptr results[], member_node_ptr member) {

    for(int race = 0; race < races; race++) {
        printf("Race Date: %s\n", results[race].race_date);
        printf("Race Start Time: %d\n", results[race].start_time);
        printf("Number of Skippers: %d\n", results[race].num_boats_competing);
        for(int boats = 0; boats < results[race].num_boats_competing; boats++) {
            find_node_by_id(member, results[race].boat_data[boats].ID);
            printf("\tTime to Complete Race in Seconds: %d\n",
                    results[race].boat_data[boats].time_to_complete_race);
        }
        printf("\n");
    }
}

void print_sorted_races(int races, race_ptr results[], member_node_ptr member) {

    race_ptr sorted_results[races];
    struct boat_data temp;

    int race, swap, boat;

    for (race = 0; race < races; race++) {
        sorted_results[race] = results[race];
    }

    for (race = 0; race < races; race++) {

        for (boat = 0; boat< (sorted_results[race].num_boats_competing -1); boat++) {
            for (swap = race + 1; swap < sorted_results[race].num_boats_competing; swap++) {
                if (sorted_results[race].boat_data[swap].time_to_complete_race >
                    sorted_results[race].boat_data[boat].time_to_complete_race) {
                    temp = sorted_results[race].boat_data[boat];
                    sorted_results[race].boat_data[boat] = sorted_results[race].boat_data[swap];
                    sorted_results[race].boat_data[swap] = temp;
                }
            }
        }
    }
    print_races(races, results, member);
}

推荐答案

通过尝试滚动你自己的排序例程而不是使用 qsort 由 C 库提供.使用 qsort,您只需编写一个 compare 函数来比较 race_nodeboat_data[] 数组成员的元素代码>.比较函数原型为:

You are making things much harder and much more error prone by trying to roll-your-own sort routine rather than using qsort provided by the C library. With qsort all you need to do is write a compare function that compares elements of the boat_data[] array member of race_node. The compare function prototype is:

 int compare (const void *a, const void *b)

所有ab 所在的位置,都是指向数组boat_data[] 元素的指针.因此,在 compare 中,您只需将 ab 转换为正确的类型(例如 structboat_node const *pa = a, *pb = b; 或者如果您在第一个结构体上完成了 typedef,只需 boat_node const *pa = a, *pb = b;).

Where all a and b are, are pointers to elements of the array boat_data[]. So within compare you simply need to cast a and b to the correct type (e.g. struct boat_node const *pa = a, *pb = b; or if you complete your typedef on your first struct, simply boat_node const *pa = a, *pb = b;).

然后比较 pa->time_to_complete_racepb->time_to_complete_race 返回 -1 如果 pa->time_to_complete_race 排序 before pb->time_to_complete_race1 如果 pb->time_to_complete_race 排序 之前 pa->time_to_complete_race,或者 0 如果它们相等(注意:完全一样 strcmp() 确实)

Then compare pa->time_to_complete_race and pb->time_to_complete_race returning -1 if pa->time_to_complete_race sorts before pb->time_to_complete_race or 1 if pb->time_to_complete_racesorts before pa->time_to_complete_race, or 0 if they are equal (note: exactly the way strcmp() does)

你的 compare 函数是:

int compare (const void *a, const void *b)
{
    boat_node const *pa = a, *pb = b;

    return (pa->time_to_complete_race > pb->time_to_complete_race) -
            (pa->time_to_complete_race < pb->time_to_complete_race);
}

注意:在完成typedef后,例如

typedef struct boat_data {
    int ID;
    int time_to_complete_race;
    int points;
} boat_node;

然后对作为 race_node Race 成员的 boat_data[] 数组进行排序,您只需调用:

Then to sort your boat_data[] array which is a member of race_node race , all you do is call:

    qsort (race.boat_data, race.num_boats_competing, 
            sizeof *race.boat_data, compare);

(完成!)

新的 C 程序员常常对使用 qsort 犹豫不决,因为他们不知道如何编写 compare 函数.在您了解 ab 只是指向 元素的任何要排序的元素这一事实之后,您可以轻松地提供一个强制转换正确的类型,然后进行比较,告诉 qsort 您希望它如何排序.

New C programmers are often hesitant to use qsort because they don't know how to write the compare function. After you make friends with the fact that a and b are just pointers to elements of whatever you are sorting, you can easily provide a cast to the proper type and then a comparison that tells qsort how you want it sorted.

在这种情况下,您只需要按 time_to_complete_race 排序的 boat_data[] 数组.return (a > b) - (a < b) 形式只是一种避免潜在溢出的简便方法,如果您想 return a - b; 其中,例如,a 是一个大的负整数,b 是一个大的正整数.

In this case you simply want the array of boat_data[] sorted by time_to_complete_race. The return (a > b) - (a < b) form is simply a convenient way to avoid potential overflow were you tempted to return a - b; where, e.g., a is a large negative integer and b a large positive integer.

完整示例

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

#define MAX_BOAT_NUMBER 10

typedef struct boat_data {
    int ID;
    int time_to_complete_race;
    int points;
} boat_node;

typedef struct race_result {
    char race_date[80];
    int start_time;
    int num_boats_competing;
    boat_node boat_data[MAX_BOAT_NUMBER];
} race_node;

int compare (const void *a, const void *b)
{
    boat_node const *pa = a, *pb = b;

    return (pa->time_to_complete_race > pb->time_to_complete_race) -
            (pa->time_to_complete_race < pb->time_to_complete_race);
}

int main (void) {

    race_node race = { .race_date = "11/26/19",
                       .start_time = 1400,
                       .num_boats_competing = 3,
                       .boat_data = {{ 1, 23, 0 },
                                     { 2, 21, 0 },
                                     { 3, 22, 0 }} };

    qsort (race.boat_data, race.num_boats_competing, 
            sizeof *race.boat_data, compare);

    for (int i = 0; i < race.num_boats_competing; i++)
        printf ("%2d  %4d  %d\n", race.boat_data[i].ID,
                race.boat_data[i].time_to_complete_race,
                race.boat_data[i].points);
}

示例使用/输出

points 成员都剩下0:

$ ./bin/boat_race
 2    21  0
 3    22  0
 1    23  0

比尝试编写自己的排序要容易得多.仔细检查一下,如果您还有其他问题,请告诉我.

Much easier than trying to write your own sort. Look things over and let me know if you have further questions.

这篇关于如何对嵌套在结构数组中的结构数组进行排序 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆