C++對象排序的比較你了解嗎
1.對象比較介紹
在排序中進(jìn)行交換的前提主要是進(jìn)行對象間的 比較、
而常見的排序是對一個數(shù)組排序,然后對每個數(shù)組內(nèi)容進(jìn)行比較與交換、
如果是對一個class進(jìn)行排序,則需要進(jìn)行關(guān)鍵字成員進(jìn)行比較,需要重寫下面幾個操作符:
- bool operator == (const class& t); // 返回ture則表示相等
- bool operator != (const class& t); // 和==相等操作符返回值相反
- bool operator <(const class& t); // 返回true則當(dāng)前對象小于t對象
- bool operator > (const class& t);
- bool operator <=(const class& t);
- bool operator >=(const class& t);
比如將學(xué)生成績單按數(shù)學(xué)成績由高到低排序,如果數(shù)學(xué)成績相同的學(xué)生再按英語成績的高低等級排序。
2.代碼實現(xiàn)
代碼如下所示:
#include <iostream>
using namespace std;
class Student {
int number; // 學(xué)號
int mathScore; // 數(shù)學(xué)成績
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++函數(shù)參數(shù)匹配規(guī)則示例小結(jié)
這篇文章主要介紹了C++函數(shù)參數(shù)匹配規(guī)則,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
Ubuntu中使用VS Code與安裝C/C++插件的教程詳解
這篇文章主要介紹了Ubuntu中使用VS Code與安裝C/C++插件的教程詳解,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

