【发布时间】:2015-04-24 01:21:20
【问题描述】:
我在 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);
如何比较两个或多个不同结构的单个字段?假设我知道每个结构包含什么
【问题讨论】:
标签: c list structure abstraction