gpt4 book ai didi

c - 比较结构以便对列表进行排序的函数

转载 作者:行者123 更新时间:2023-11-30 17:15:52 25 4
gpt4 key购买 nike

我在 C 中有一个抽象数据类型,事物列表,ist 节点有一个 void* 指针,我想做的是创建一个函数来比较不同结构的特定字段,以便对我的列表进行排序事物。

typedef struct node{
char *name;
void *thing;
struct node *next;
}Node;

这是我正在使用的节点,我已经创建了整数列表、结构列表和两者的比较函数,但我不知道如何对不同的结构执行比较函数。例如:

给定这些类型:

 typedef struct main{
float weight;
char*model;
float maxspeed;
}Main;


typedef struct airplane{
float weight;
float maxspeed;
}Airplane;

typedef struct car{
char*model;
float maxspeed;
}Car;

这就是函数,所以你知道我想要做什么,它不起作用,Main 具有在一个或另一个结构中不存在的字段。

int comparefunction(void*a,void*b){
Main a1, a2;
a1=*(Main*)a;
a2=*(Main*)b;

return a1.weight-a2.weight;
}

此函数(不起作用)作为参数传递给链接节点的函数,以便使用比较函数。

//insert prototype: 
//insert(Node*listp,Node*newp,int(*func_comp)(void*,void*));

list=insert(list,newItem(&car1),comparefunction);
list=insert(list,newItem(&airplane1),comparefunction);
list=insert(list,newItem(&airplane2),comparefunction);

我如何比较两个或多个不同结构的单个字段?假设我知道每个结构包含什么

最佳答案

如果您想比较有些相似的事物,您可以研究 union 。

struct attributes{
float weight;
// other common things?
};

struct thing {
enum { Car, Main, Airplane } type;
struct attributes attrs;
union {
struct Car car;
struct Main main;
struct Airplane airplane;
} other_thing;
};

您需要更改列表来存储事物结构,该结构封装了所有可能的类型。每种类型的公共(public)元素都被提取到属性结构中。然后,您的比较函数将对事物结构的属性结构进行操作。此处使用并集仅在结构体中为最大的并集元素创建足够的空间,这样您就不会浪费空间来存储所有三个结构体而只使用一个结构体。

关于c - 比较结构以便对列表进行排序的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com