網站首頁 編程語言 正文
1.對象比較介紹
在排序中進行交換的前提主要是進行對象間的?比較、
而常見的排序是對一個數組排序,然后對每個數組內容進行比較與交換、
如果是對一個class進行排序,則需要進行關鍵字成員進行比較,需要重寫下面幾個操作符:
- 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);
比如將學生成績單按數學成績由高到低排序,如果數學成績相同的學生再按英語成績的高低等級排序。
2.代碼實現
代碼如下所示:
#includeusing namespace std; class Student { int number; // 學號 int mathScore; // 數學成績 int enScore; // 英語成績 public: Student() { } Student(int number, int mathScore, int enScore) { this->number = number; this->mathScore = mathScore; this->enScore = enScore; } void printString() { cout<<"number:"< (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: "<
運行打印:
總結
原文鏈接:https://blog.csdn.net/qq_37997682/article/details/122464562
相關推薦
- 2022-04-01 K8s產生ERROR的解決方法
- 2022-07-02 iview中的表格render搭配使用Tooltip 文字提示
- 2022-08-03 Shell常用服務器日志分析命令總結_linux shell
- 2022-05-25 使用Python繪制三種概率曲線詳解_python
- 2023-01-05 Kotlin的空安全處理方式詳解_Android
- 2022-11-10 golang?常用定時任務匯總_Golang
- 2022-10-16 Android基于方法池與回調實現登錄攔截的場景_Android
- 2023-04-19 Element UI Table常用使用方法(header-cell-style;表頭中的全選框取消
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支