0
我想排序如下结构:快速排序,以结构排序
typedef struct thing {
char *text;
int count;
} *Item;
我创建一个额外的载体这样的结构进行排序:
Item items[nr_of_items];
... here is a loop to place the items inside the vector items ...
qsort(items, nr_of_items, sizeof(Item), cmpItem);
这里是比较功能:
int cmpItem(const void *a, const void *b) {
const Item item_a = (const Item)a;
const Item item_b = (const Item)b;
/* Return 1 or -1 if members are not equal */
if (item_a->count > item_b->count) return 1;
if (item_a->count < item_b->count) return -1;
/* Return 1 or -1 if members are not equal */
if (strcmp (item_a->text, item_b->text) > 0) return 1;
if (strcmp (item_a->text, item_b->text) < 0) return -1;
/* Return 0 if both members are equal in both structures */
return 0;
}
矢量正在正确创建,但它没有被排序。难道我做错了什么?任何帮助表示赞赏。
这可能有很多重复的。你需要'const Item item_a = *(const Item *)a'。 –
谢谢,我曾尝试过,但我总是得到一个分段错误错误。也许这是因为我有我的结构typedef *项目? –
如果将'Item'作为指针进行typedeff,* if *原始'items'数组中的所有指针设置正确,它应该可以工作。 'items []'确实包含'struct thing'的有效指针的数量'nr_of_items'? (以及“文本”指针的分配情况如何,你确定这些指针也可以吗?) –