我会考虑使用标准排序实现使用的方法 - 即使用接收 2 个指针的用户定义比较函数。然后,您可以使用这些指针来定位元素,并从那里访问和比较您感兴趣的成员。这也避免了不必要的内存复制。
考虑以下用于比较整数的函数:
int compareIntAsc(const void *int1, const void *int2)
{
int *num1 = (int*)int1;
int *num2 = (int*)int2;
return *num1 - *num2;
}
现在考虑一个比较某些结构的计数成员的方法
int compareNodeCountAsc(const void *node1, const void *node1)
{
return (pHuffmanNode)(node1))->charCount - ((pHuffmanNode)(node2))->charCount;
}
如果将数组中两个元素的地址传递给这样的函数,则可以比较记录或键。
例如,将元素 0 与其他所有元素进行比较
代码
typedef struct {
int record;
int key;
} leaf_entry, *pLeafEntry;
int compLeafKeyAsc(void *leaf1, void *leaf2)
{
leaf_entry *p1, *p2;
p1 = (leaf_entry *)leaf1;
p2 = (leaf_entry *)leaf2;
return p1->key - p2->key;
}
void printLeaf(pLeafEntry leaf)
{
printf("----- leaf -------\n");
printf("record: %d\n", leaf->record);
printf("key: %d\n", leaf->key);
}
void demo()
{
const int nElems = 16;
leaf_entry leafArray[nElems];
pLeafEntry firstElement;
int i;
for (i=0;i<nElems;i++)
{
leafArray[i].record = (rand()%51) + 100; // record is [100..150]
leafArray[i].key = (rand()%128); // key is [0..127]
printLeaf(&leafArray[i]);
}
//e.g compare element 0 to every other element
firstElement = &leafArray[0];
for (i=1; i<nElems; i++)
{
printf("%d", firstElement->key );
int result = compLeafKeyAsc(firstElement, &leafArray[i]);
if (result < 0)
printf(" is less than ");
else if (result > 0)
printf(" is greater than ");
else
printf(" is equal to ");
printf("%d\n", leafArray[i].key);
}
}
输出
----- leaf -------
record: 141
key: 35
----- leaf -------
record: 110
key: 4
----- leaf -------
record: 144
key: 108
----- leaf -------
record: 103
key: 46
----- leaf -------
record: 134
key: 16
----- leaf -------
record: 144
key: 113
----- leaf -------
record: 125
key: 59
----- leaf -------
record: 116
key: 107
----- leaf -------
record: 137
key: 38
----- leaf -------
record: 133
key: 60
----- leaf -------
record: 106
key: 12
----- leaf -------
record: 126
key: 25
----- leaf -------
record: 137
key: 94
----- leaf -------
record: 130
key: 28
----- leaf -------
record: 132
key: 55
----- leaf -------
record: 141
key: 94
35 is greater than 4
35 is less than 108
35 is less than 46
35 is greater than 16
35 is less than 113
35 is less than 59
35 is less than 107
35 is less than 38
35 is less than 60
35 is greater than 12
35 is greater than 25
35 is less than 94
35 is greater than 28
35 is less than 55
35 is less than 94