在 C++ 中使用 std::sort 對結構體陣列進行排序時,常需要依據多個欄位進行比較。例如:先按欄位 a 降序排列,若 a 相同則按 b 降序,若 b 也相同則按字串 s 升序。本文將詳細說明如何撰寫符合嚴格弱序的比較函數 cmp,並提供完整程式碼範例。
struct Data {
std::string s;
int a, b;
} x[100];
比較函數必須回傳 bool,且滿足:若第一個引數應排在第二個引數之前則回傳 true,否則回傳 false。針對三級排序邏輯,建議採用逐層判斷的寫法:
bool cmp(const Data& n, const Data& m) {
if (n.a != m.a) {
return n.a > m.a; // a 降序
}
if (n.b != m.b) {
return n.b > m.b; // b 降序
}
return n.s < m.s; // s 升序
}
const Data& 避免不必要的複製,提升效能。std::string 已內建 operator<,可直接比較字典序,無需使用 strcmp。#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
struct Data {
std::string s;
int a, b;
};
bool cmp(const Data& n, const Data& m) {
if (n.a != m.a) return n.a > m.a;
if (n.b != m.b) return n.b > m.b;
return n.s < m.s;
}
int main() {
std::vector vec = {
{"apple", 3, 5},
{"banana", 3, 5},
{"cherry", 2, 10},
{"date", 3, 4}
};
std::sort(vec.begin(), vec.end(), cmp);
for (const auto& d : vec) {
std::cout << d.s << ' ' << d.a << ' ' << d.b << '\n';
}
return 0;
}
return n.a > m.a || n.b > m.b || n.s < m.s; 會導致邏輯錯誤,因為只要第一個條件為真就會直接回傳,忽略後續欄位。const。> 或 <)。透過逐層判斷的比較函數,即可輕鬆實現結構體的多欄位排序。掌握此技巧,能讓你在處理複雜資料排序時更加得心應手。