这篇文章主要为大家详细介绍了C++对象排序的比较,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
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.代码实现
代码如下所示:
#include <iostream>
using 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:"<<number <<" mathScore:" << mathScore <<" enScore:"<< enScore << endl;
}
bool operator == (const Student& t) {
return mathScore == t.mathScore && enScore == t.enScore;
}
// 不等于则调用==操作符,取反即可
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();
}
运行打印:
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程学习网的更多内容!
沃梦达教程
本文标题为:C++对象排序的比较你了解吗


猜你喜欢
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- C++ 数据结构超详细讲解顺序表 2023-03-25
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- C语言详解float类型在内存中的存储方式 2023-03-27
- C语言qsort()函数的使用方法详解 2023-04-26
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- Easyx实现扫雷游戏 2023-02-06
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- ubuntu下C/C++获取剩余内存 2023-09-18
- Qt计时器使用方法详解 2023-05-30