学无先后,达者为师

网站首页 编程语言 正文

C++对象排序的比较你了解吗_C 语言

作者:诺谦   更新时间: 2022-04-29 编程语言

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 
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:"< (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

栏目分类
最近更新