定義一個 Student 類,包含 string x 屬性,需要將對象數組按 x 從大到小排序。許多初學者嘗試直接使用 std::sort 卻發現無法編譯或結果錯誤。
std::sort 接受第三個參數為比較函數(或函數對象、Lambda),用於定義排序規則。以下是完整可編譯範例:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Student {
public:
string x; // 要排序的屬性
};
// 比較函數:返回 true 表示 a 應排在 b 前面(此處為降序)
bool comp(const Student &a, const Student &b) {
return a.x > b.x;
}
int main() {
Student a[5];
for (int i = 0; i < 5; ++i) {
cin >> a[i].x;
}
sort(a, a + 5, comp); // 使用自定義比較函數
for (int i = 0; i < 5; ++i) {
cout << a[i].x << " ";
}
cout << endl;
return 0;
}
sort(a, a + 5, [](const Student &a, const Student &b) {
return a.x > b.x;
});
const T& 參數,返回 bool。private,需將比較函數聲明為 friend 或提供公有 getter。return a.x != b.x ? a.x > b.x : a.y < b.y;。掌握 std::sort 搭配自定義比較器,是 C++ 處理複雜數據排序的核心技能。靈活運用 Lambda 可大幅簡化代碼。