C++對象排序的比較你了解嗎
1.對象比較介紹
在排序中進行交換的前提主要是進行對象間的 比較、
而常見的排序是對一個數(shù)組排序,然后對每個數(shù)組內(nèi)容進行比較與交換、
如果是對一個class進行排序,則需要進行關(guān)鍵字成員進行比較,需要重寫下面幾個操作符:
- bool operator == (const class& t); // 返回ture則表示相等
- bool operator != (const class& t); // 和==相等操作符返回值相反
- bool operator <(const class& t); // 返回true則當前對象小于t對象
- bool operator > (const class& t);
- bool operator <=(const class& t);
- bool operator >=(const class& t);
比如將學生成績單按數(shù)學成績由高到低排序,如果數(shù)學成績相同的學生再按英語成績的高低等級排序。
2.代碼實現(xiàn)
代碼如下所示:
#include <iostream> using namespace std; class Student { int number; // 學號 int mathScore; // 數(shù)學成績 int enScore; // 英語成績 public: Student() { } Student(int number, int mathScore, int enScore) { this->number = number; this->mathScore = mathScore; this->enScore = enScore; } void printString() { cout<<"number:"<<number <<" mathScore:" << mathScore <<" enScore:"<< enScore << endl; } bool operator == (const Student& t) { return mathScore == t.mathScore && enScore == t.enScore; } // 不等于則調(diào)用==操作符,取反即可 bool operator != (const Student& t) { return !(*this == t); } bool operator <(const Student& t) { return mathScore < t.mathScore || (mathScore == t.mathScore && enScore < t.enScore); } bool operator > (const Student& t) { return mathScore > t.mathScore || (mathScore == t.mathScore && enScore > t.enScore); } bool operator <=(const Student& t) { return !(*this > t); } bool operator >=(const Student& t) { return !(*this < t); } };
測試代碼如下所示(使用上章我們寫的冒泡排序):
Student arr[8] = { Student(1,65,77), Student(2,44,65), Student(3,75,65), Student(4,65,77), Student(5,98,97), Student(6,86,96), Student(7,92,63), Student(8,32,78) }; bubbleSort(arr, 8); // 使用冒泡排序 升序 cout<<"ascend: "<<endl; for (int i = 0; i < 8; ++i) { arr[i].printString(); } cout<<endl; bubbleSort(arr, 8, false); // 使用冒泡排序 降序 cout<<endl<<"descend: "<<endl; for (int i = 0; i < 8; ++i) { arr[i].printString(); }
運行打印:
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C++中memcpy函數(shù)的使用以及模擬實現(xiàn)
memcpy是c和c++使用的內(nèi)存拷貝函數(shù),本文主要介紹了C++中memcpy函數(shù)的使用以及模擬實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07C++實現(xiàn)學生選課系統(tǒng)的思路與詳細過程
C語言是在國內(nèi)外廣泛使用的一種計算機語言,下面這篇文章主要給大家介紹了關(guān)于C++實現(xiàn)學生選課系統(tǒng)的思路與詳細過程,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01