`sort` 預設升序,為何傳入自定義 `compare` 函數後變降序?
`std::sort` 內部使用 **嚴格弱序**。比較函數 `comp(a, b)` 返回 `true` 表示 **`a` 應排在 `b` 之前**(即 `a < b`)。
bool comp(const Type &a, const Type &b); // 或函數物件、lambda
要求:
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector v = {5, 2, 9, 1, 5};
// 降序
std::sort(v.begin(), v.end(), [](int a, int b){ return a > b; });
// 輸出: 9 5 5 2 1
// 依絕對值升序
std::sort(v.begin(), v.end(), [](int a, int b){ return std::abs(a) < std::abs(b); });
// 結構體按特定欄位排序
struct Student { std::string name; int score; };
std::vector students = {{"A", 80}, {"B", 90}, {"C", 70}};
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b){ return a.score > b.score; }); // 分數降序
}