首页 > 编程技术 > C语言

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

发布时间:2022-2-25 22:10 作者:诺谦

1.对象比较介绍

在排序中进行交换的前提主要是进行对象间的 比较、

而常见的排序是对一个数组排序,然后对每个数组内容进行比较与交换、

如果是对一个class进行排序,则需要进行关键字成员进行比较,需要重写下面几个操作符:

比如将学生成绩单按数学成绩由高到低排序,如果数学成绩相同的学生按英语成绩的高低等级排序。

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

运行打印:

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注猪先飞的更多内容!  

原文出处:https://blog.csdn.net/qq_37997682/article/details/122464562

标签:[!--infotagslink--]

您可能感兴趣的文章: