3.C++-对象排序比较

 在上章我们学习了2.C++-选择排序、冒泡排序、插入排序、希尔排序、归并排序、快速排序_抵抗时间扭曲,坚持做一件有意义的事-CSDN博客

所以本章实现进行对象数组排序


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();
    }

运行打印:

如上图所示,始终以数学成绩关键字成员优先

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诺谦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值