網站首頁 編程語言 正文
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-08 Android接入阿里云熱修復介紹_Android
- 2022-10-03 python接口自動化使用requests庫發送http請求_python
- 2022-04-18 C語言數組全面總結梳理_C 語言
- 2022-03-30 C#中的out參數、ref參數和params可變參數用法介紹_C#教程
- 2022-04-11 matlab模擬退火算法單約束車間流水線調度解決實現及示例_C 語言
- 2024-03-14 ThreadLocal使用,配合攔截器HandlerInterceptor使用
- 2022-08-23 python數據分析繪圖可視化_python
- 2023-03-16 Android?OpenCV基礎API清晰度亮度識別檢測_Android
- 最近更新
-
- 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同步修改后的遠程分支