簡體   English   中英

q對結構排序

[英]qSort to sort structures

我正在嘗試對以下結構進行排序:

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;

}

向量已正確創建,但未排序。 難道我做錯了什么? 任何幫助表示贊賞。

qsortcompar回調函數接收兩個參數,它們指向要比較的對象,即,指向items數組中兩個元素的指針。 這意味着ab都是Item指針,而不是Item本身的指針。 您需要對此進行更改:

const Item *pa = a;
const Item *pb = b;
const Item item_a = *pa;
const Item item_b = *pb;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM