首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ sort 函數第三個參數(比較函數)詳解:自定義排序規則

     編輯:程式設計疑難解答

問題

`sort` 預設升序,為何傳入自定義 `compare` 函數後變降序?

原理

`std::sort` 內部使用 **嚴格弱序**。比較函數 `comp(a, b)` 返回 `true` 表示 **`a` 應排在 `b` 之前**(即 `a < b`)。

  • 預設 `comp = std::less` → `a < b` → 升序。
  • 自定義 `comp = [](int a, int b){ return a > b; }` → `a > b` 時返回 `true` → 視為 `a` 小於 `b` → 結果為降序。

比較函數簽名

bool comp(const Type &a, const Type &b); // 或函數物件、lambda

要求:

  1. **不可變性**:不修改 `a`、`b`。
  2. **嚴格弱序**:自反性、傳遞性、等價性。
  3. **回傳 `bool`**:`true` 表示 `a` 排在 `b` 前面。

範例

#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; }); // 分數降序
}

常見錯誤

  • 寫成 `return a >= b;` → 違反嚴格弱序(相等時也返回 true),導致未定義行為(如無限迴圈、崩潰)。
  • 捕獲外部變量未加 `mutable` 或引用生命週期錯誤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved