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

如果數據量很大的話,不建議使用第二種方法排序可能會超時。

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