C++运算符重载自定义结构体比较

当对结构体类型进行比较时可以在外面写一个compare()函数,但是也要知道还有其他的办法的

对 < 运算符进行了重载,通俗一点就是自己定义 < 运算符的意义,这段代码就是让小于变成了“大于”那么sort函数排序时从小到大的排序就变成了从大到小排序,当id相同时按从小到大排

struct node{
	int id,score;
	bool operator <(const node &x)const{
		if(id==x.id) return score<x.score;
		return id>x.id;
	}
};
也可以使用friend友元函数,这个代码与上面的用法一模一样
struct node{
	int id,score;
	friend operator < (node a,node b){
		if(a.id==b.id) return a.score<b.score;
		return a.id>b.id;
	}
};

猜你喜欢

转载自blog.csdn.net/AGNING/article/details/106221385