小于操作符重载与对象排序

这篇博客介绍了如何在C++中通过重载小于号操作符来实现对象排序,使得vector、list、map等容器能够对自定义对象进行排序。示例代码展示了一个Student结构体,比较了score和name属性,实现了基于分数和姓名的降序排序。通过std::sort函数,展示了如何对包含Student对象的vector进行排序并打印排序结果。
摘要由CSDN通过智能技术生成

C++自学精简教程 目录(必读)

对象排序需要用户提供小于号操作符重载。

这样以来,vector list map 等支持排序的容器就可以对对象进行排序,或者用算法在容器上排序。

具体看下面的例子:

#include <vector> //vector
#include <algorithm> //std::sort
#include <iostream> // std::cout
#include <iomanip> // std::setw
#include <string> // std::string

struct Student
{
	//for cout<<student fout<<student
	friend std::ostream& operator<<(std::ostream& os, const Student& student);
	//for std::sort
	bool operator<(const Student& other);

	//members
	std::string name;
	int score;
};

std::ostream& operator<<(std::ostream& os, const Student& student)
{
	// score use 4 width when print, name use 10 width for print
	os << std::setw(4) << student.score << std::setw(10) << student.name;
	return os;
}

bool Student::operator<(const Student& other)
{
	//(1) compare score
	if (score < other.score)
	{
		//for higher score first show
		return false;
	}
	else if(score == other.score)
	{
		//(2) compare other detail member
		return name < other.name;
	}
	//(1) compare score
	else
	{
		//for higher score first show
		return true;
	}
}

int main()
{
	//init all students's data
	std::vector<Student> students{
		{"zhangsan", 700},
		{"lisi", 680},
		{"wanger", 699},
		{"mazi", 699},
		{"zhangfei", 700},
		{"liubei", 590},
	};

	//use stu1 < stu2 for sorting
	std::sort(students.begin(), students.end());

	for (std::vector<Student>::const_iterator itr = students.begin();
		itr != students.end(); ++itr)
	{
		//use operator<<(std::ostream& os, const Student& student)
		std::cout << *itr << std::endl;
	}

	return 0;
}

程序输出如下:

怎么样,你学会了吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

C++程序员Carea

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

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

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

打赏作者

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

抵扣说明:

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

余额充值