这篇文章主要介绍C++中对象排序的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
在排序中进行交换的前提主要是进行对象间的 比较、
而常见的排序是对一个数组排序,然后对每个数组内容进行比较与交换、
如果是对一个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);
比如将学生成绩单按数学成绩由高到低排序,如果数学成绩相同的学生再按英语成绩的高低等级排序。
代码如下所示:
#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++中对象排序的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。