C++定义结构体的优先级

假设存在一个叫Point(x,y)的结构体,我们写以x值更小有更高的优先级,常见的写法如下。

struct Point{
	int x,y;
	friend bool operator <(Point A,Point B){
		return A.x<B.x;
	}//friend关键字,让该函数可以访问结构体的所有属性
};
struct Point{
	int x,y;
};
bool cmp(Point A,Point B){
	return A.x<B.x;
}//排序时调用比较函数cmp,sort(,,cmp);
struct Point{
	int x,y;
	bool operator <(const Point &rhs)const {
		return x<rhs.x;//可以把x理解为1.2中的A.x,rhs.x理解为B.x
	}
};

如果数据量很大的话,不建议使用第二种方法排序可能会超时。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章