Когда у вас есть данные вроде двух разных значений, которые «принадлежат друг другу», вы не помещаете их в два разных массива.Вместо этого вы делаете struct
, который может содержать оба значения.После этого вы делаете array of the struct
.Например:
// Define a type to hold both percentage and name
typedef struct
{
float percentage;
char caseName[28];
} CaseType;
// In some function make the array
CaseType year2010Cases[4] = {
{11.2, "Respiratory Tract Infection"},
{8.9, "Diabetes Mellitus"},
{15.6, "Hyperlipidemia"},
{15.9, "Hypertensive Disease"}};
Одним из преимуществ этого является то, что два значения, которые принадлежат друг другу, всегда остаются вместе.Еще одним преимуществом является то, что мы можем использовать стандарт qsort
для сортировки данных.Как:
typedef struct
{
float percentage;
char caseName[28];
} CaseType;
// Compare function used by qsort
int compar(const void * a, const void * b)
{
CaseType* pa = (CaseType*)a;
CaseType* pb = (CaseType*)b;
if (pa->percentage > pb->percentage) return 1;
if (pa->percentage < pb->percentage) return -1;
return 0;
}
int main(void)
{
CaseType year2010Cases[4] = {
{11.2, "Respiratory Tract Infection"},
{8.9, "Diabetes Mellitus"},
{15.6, "Hyperlipidemia"},
{15.9, "Hypertensive Disease"}};
printf("Original list:\n");
for (int c = 0; c < 4; c++)
printf("%.1f - %s\n", year2010Cases[c].percentage, year2010Cases[c].caseName);
// Sort the array with a single call of qsort
qsort(year2010Cases, 4, sizeof *year2010Cases, compar);
printf("-------------------------------------\n");
printf("Sorted list:\n");
for (int c = 0; c < 4; c++)
printf("%.1f - %s\n", year2010Cases[c].percentage, year2010Cases[c].caseName);
return 0;
}
Вывод:
Original list:
11.2 - Respiratory Tract Infection
8.9 - Diabetes Mellitus
15.6 - Hyperlipidemia
15.9 - Hypertensive Disease
-------------------------------------
Sorted list:
8.9 - Diabetes Mellitus
11.2 - Respiratory Tract Infection
15.6 - Hyperlipidemia
15.9 - Hypertensive Disease