stable_sort 是 C++ 標準函式庫(<algorithm>)提供的排序函式。
它與 sort() 類似,但 可以保證相同數值的元素維持原本的順序。
時間複雜度:O(N log N),但比 sort() 可能稍慢,因為它需要維持穩定性。
Lambda 表達式 [](const Student &a, const Student &b) { return a.total > b.total; }
這是一個比較函式,用來告訴 stable_sort() 如何比較兩個學生 (a 和 b)。
拆解說明
[](const Student &a, const Student &b) { return a.total > b.total; }
[] 代表Lambda 表達式的開頭。
(const Student &a, const Student &b) 代表兩個要比較的學生。
{ return a.total > b.total; }
如果 a.total 大於 b.total,則 a 會排在 b 前面(即「由高到低」排序)。
否則 b 會在 a 前面。
為什麼使用 stable_sort() 而不是 sort()?
題目要求 「當總分相同時,維持原輸入順序」。
sort() 不保證 相同數值的元素維持輸入順序。
stable_sort() 可以保證 相同總分的學生按照輸入順序排列。
範例
假設有以下學生資料:
vector<Student> students = {
{"Alice", 80, 85, 90, 255, 85.0},
{"Bob", 90, 80, 85, 255, 85.0}, // 總分與 Alice 相同
{"Charlie", 70, 75, 80, 225, 75.0}
};
排序前:
Alice 255
Bob 255
Charlie 225
當我們使用 stable_sort() 排序:
stable_sort(students.begin(), students.end(), [](const Student &a, const Student &b) {
return a.total > b.total;
});
排序後:
Alice 255 (因為 Alice 先輸入,維持順序)
Bob 255 (Bob 之後輸入)
Charlie 225
這樣就能 符合題目要求:
總分由高到低
相同總分時,維持原輸入順序
總結
stable_sort(students.begin(), students.end(), [](const Student &a, const Student &b) {
return a.total > b.total;
});
這行程式碼的作用
讓學生依「總分由高到低」排序。
如果總分相同,則保持原輸入順序(因為 stable_sort 會維持相同數值的順序)。
確保符合題目要求! |