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

C++ 類對象數組按指定屬性排序完整指南

     編輯:程式設計疑難解答

問題場景

定義一個 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;
}

進階寫法:Lambda 表達式 (C++11)

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 可大幅簡化代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved