std::sort (需含 `
struct AssessTypeInfo {
unsigned int m_uiType; // 類型 ID
char m_szName[64]; // 類型名稱
unsigned int m_uiTotal; // 總分數
};
// 升序:依 m_uiType 由小到大
bool lessmark(const AssessTypeInfo &s1, const AssessTypeInfo &s2) {
return s1.m_uiType < s2.m_uiType;
}
// 降序:依 m_uiType 由大到小
bool greatermark(const AssessTypeInfo &s1, const AssessTypeInfo &s2) {
return s1.m_uiType > s2.m_uiType;
}
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
int main() {
vector<AssessTypeInfo> ctn;
AssessTypeInfo a1 = {1}, a2 = {2}, a3 = {3};
ctn.push_back(a1); ctn.push_back(a2); ctn.push_back(a3);
// 升序
sort(ctn.begin(), ctn.end(), lessmark);
for (int i = 0; i < 3; ++i) printf("%d\n", ctn[i].m_uiType); // 1 2 3
// 降序
sort(ctn.begin(), ctn.end(), greatermark);
for (int i = 0; i < 3; ++i) printf("%d\n", ctn[i].m_uiType); // 3 2 1
return 0;
}
sort(v.begin(), v.end(), [](const A& a, const A& b){ return a.key < b.key; });operator() 的結構體,可攜帶狀態。struct ByName { bool operator()(const A& a, const A& b) const { return strcmp(a.name, b.name) < 0; } };sort(v.begin(), v.end(), [](const A& a, const A& b){ return tie(a.key1, a.key2) < tie(b.key1, b.key2); }); (需 `std::sort 不保證穩定 (相等元素相對順序可能改變),需穩定排序請用 std::stable_sort。const&。優先使用 Lambda + 範圍-based for + 結構化綁定 (C++17) 撰寫清晰、高效的排序邏輯;避免舊式函數指標與全域比較函數。