您好,登錄后才能下訂單哦!
這篇文章主要介紹C++中對(duì)象排序的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
在排序中進(jìn)行交換的前提主要是進(jìn)行對(duì)象間的 比較、
而常見的排序是對(duì)一個(gè)數(shù)組排序,然后對(duì)每個(gè)數(shù)組內(nèi)容進(jìn)行比較與交換、
如果是對(duì)一個(gè)class進(jìn)行排序,則需要進(jìn)行關(guān)鍵字成員進(jìn)行比較,需要重寫下面幾個(gè)操作符:
bool operator == (const class& t); // 返回ture則表示相等
bool operator != (const class& t); // 和==相等操作符返回值相反
bool operator <(const class& t); // 返回true則當(dāng)前對(duì)象小于t對(duì)象
bool operator > (const class& t);
bool operator <=(const class& t);
bool operator >=(const class& t);
比如將學(xué)生成績(jī)單按數(shù)學(xué)成績(jī)由高到低排序,如果數(shù)學(xué)成績(jī)相同的學(xué)生再按英語(yǔ)成績(jī)的高低等級(jí)排序。
代碼如下所示:
#include <iostream> using namespace std; class Student { int number; // 學(xué)號(hào) int mathScore; // 數(shù)學(xué)成績(jī) int enScore; // 英語(yǔ)成績(jī) 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); } };
測(cè)試代碼如下所示(使用上章我們寫的冒泡排序):
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(); }
運(yùn)行打印:
以上是“C++中對(duì)象排序的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。