需求:對結構體數組按多字段排序(如先按成績降序,成績相同再按年齡升序)。qsort 配合自定義比較函數可完美實現。
typedef struct {
char name[20];
float score; // 浮點數字段
int age;
} Student;
int cmp_student(const void* a, const void* b) {
Student* s1 = (Student*)a;
Student* s2 = (Student*)b;
// 1. 主鍵:score 降序
if (s1->score > s2->score) return -1;
if (s1->score < s2->score) return 1;
// 2. 次鍵:age 升序
if (s1->age < s2->age) return -1;
if (s1->age > s2->age) return 1;
// 3. 兜底:name 字典序
return strcmp(s1->name, s2->name);
}
Student stu[100];
int n = 50; // 實際數量
qsort(stu, n, sizeof(Student), cmp_student);
const float EPS = 1e-6;
if (fabs(s1->score - s2->score) > EPS) {
return (s1->score > s2->score) ? -1 : 1;
}
int 再比。sort(stu, stu+n, [](const Student& a, const Student& b){
if (fabs(a.score - b.score) > EPS) return a.score > b.score;
if (a.age != b.age) return a.age < b.age;
return a.name < b.name;
});
std::sort 類型安全、內聯優化、支持 Lambda,除非嵌入式環境無 STL,否則優先使用。