用类嵌套的方式对学生类进行排序

#include <iostream>
using namespace std;

class student
{
	friend class handler;
	friend bool operator>(student& stu1, student& stu2);
	friend ostream& operator<<(ostream& cout, const student& stu);
private:
	string name;
	int score;
public:
	int display()
	{
		return this->score;
	}
	student(string name =" ", int score = 0) :name(name), score(score) {}
	void input(string name, int score)
	{
		this->name = name;
		this->score = score;
	}
};

bool operator>(student& stu1, student& stu2)
{
	return stu1.score > stu2.score ? true : false;
}

ostream& operator<<(ostream& cout, const student& stu)  //重载左移运算符
{
	cout << stu.name << "  " << stu.score << endl;
	return cout;
}


class handler
{
	friend ostream& operator<<( ostream& cout, const student& stu);
private:
	student* stu;
	int size;
public:
	handler(int size) : size(size), stu(new student[size]){}
	
	~handler()
	{
		delete[] stu;
	}
	void bubble()
	{
		for (int i = 0; i < this->size - 1; i++)
		{
			for (int j = 0; j < this->size - 1 - i; j++)
			{
				if (stu[j] > stu[j + 1])   //重载 >号
				{
					student temp = stu[j];
					stu[j] = stu[j + 1];
					stu[j + 1] = temp;
				}
				
			}
		}
	}

	void input_hand(string name, int score,int pos)
	{
		this->stu[pos].name = name;
		this->stu[pos].score = score;
	}
	int handsize()
	{
		return this->size;
	}
	void myprint(int pos)
	{
		//cout << this->stu[pos].name << "  " << this->stu[pos].score << endl;
		cout << this->stu[pos]; // ==  operator<<(cout, stu[0])
	}
};

int main()
{
	handler hand(5);
	hand.input_hand("aaa", 100, 0);
	hand.input_hand("bbb", 123, 1);
	hand.input_hand("ccc", 90, 2);
	hand.input_hand("ddd", 110, 3);
	hand.input_hand("eee", 112, 4);
	
	hand.bubble();
	for (int i = 0; i < hand.handsize(); i++)
	{
		hand.myprint(i);
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值