簡體   English   中英

在嵌套結構數組上使用 qsort

[英]using qsort on a nested struct array

下面是我的 Structures 和 qsort 聲明(根據 nID 排列)

編輯:

struct items{
    int nID;
    int nQuantity;
    int nItems;
    float fPrice;
    char cItemName[21];
    char cCategory[21];
    char cItemDesc[31];
};

struct Register{
    struct items List[20];
    char cID[11];
    char cPassword[11];
    char cAddress[31];
    char cContact[16];
    char cName[21];
}; 

int main ()
{
  /*These are the contents of List[]*/
  Users[nInd].List[1].nID = 1;
  strcpy(Users[nInd].List[1].cItemName, "iPhoneMAXMAX");
  strcpy(Users[nInd].List[1].cCategory, "Gadgettronss");
  strcpy(Users[nInd].List[1].cItemDesc, "This is an iphone");
  Users[nInd].List[1].nQuantity = 1;
  Users[nInd].List[1].fPrice = 100;

  Users[nInd].List[0].nID = 50;
  strcpy(Users[nInd].List[0].cItemName, "iPhone");
  strcpy(Users[nInd].List[0].cCategory, "Gadgets");
  strcpy(Users[nInd].List[0].cItemDesc, "This is an iphone");
  Users[nInd].List[0].nQuantity = 20;
  Users[nInd].List[0].fPrice = 50;

  for (i = 0; i < 2; i++)
    qsort (&Users[nInd].List[i], 2, sizeof (struct Register), sort);

  for (i = 0; i < 2; i++)
    printf ("%11d  %20s\t %15s  \t   % 10.2f  \t\t      %2d\n", 
        Users[nInd].List[i].nID, Users[nInd].List[i].cItemName,
        Users[nInd].List[i].cCategory, Users[nInd].List[i].fPrice, 
        Users[nInd].List[i].nQuantity);
/*rest of the code*/
}

理想輸出:

產品編號 項目名稱 類別 價格 數量

1 Iphone 小工具 50.00 20

50 IphoneMAXMAX Gadgettronss 100.00 1

實際輸出:

50 IphoneMAXMAX Gadgettronss 100.00 1

1 Iphone 小工具 50.00 20

但是,我的問題是當我顯示 List[] 的內容時沒有任何變化。

這是我的 qsort 比較器函數:

int sort (const void*p, const void*q)
{
  const struct Register *ip = (struct Register*)p;
  const struct Register *iq = (struct Register*)q;

  if (ip->List[0].nID > iq->List[1].nID)
    return 1;
  else if (ip->List[0].nID < iq->List[1].nID)
    return -1;
  else
    return 0;

}

如果要使用qsortList數組中的元素進行排序,則執行 eg

qsort(Users[nInd].List, NumberOfElementsInList, sizeof(struct items), CompareItems);

這將對數組Users[nInd].ListNumberOfElementsInList第一個struct items元素進行排序。

您的比較函數接收指向數組中struct items元素的指針:

int CompareItems(const void *a, const void *b)
{
    const struct items *item_a = (const struct items *) a;
    const struct items *item_b = (const struct items *) b;

    if (item_a->nID > item_b->nID)
        return 1;
    else if (item_a->nID < item_b->nID)
        return -1;
    else
        return 0;
}

如果您只想“排序” Users[nInd].List數組中的前兩個元素,則不需要qsort函數,只需直接比較兩個元素並在需要時交換:

if (Users[nInd].List[0].nID > Users[nInd].List[1].nID)
{
    // Swap the items as index 0 and 1, thereby sorting them
    struct items temp_item = Users[nInd].List[0];
    Users[nInd].List[0] = Users[nInd].List[1];
    Users[nInd].List[1] = temp_item;
}

暫無
暫無

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

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