sort 及 priority_queu 中struct結構體的重載

關於sort,priority_queue 的struct中自定義的排序方法會產生不同的序列

看例子:

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct Demo{
	int x, y;
	bool operator<(const Demo &A)const{
		return x < A.x;
	}
};
vector<Demo>D;
priority_queue<Demo>pq;
int main(){
	for (int i = 0; i < 5; i++){
		int X, Y; cin >> X >> Y;
		Demo temp; temp.x = X, temp.y = Y;
		D.push_back(temp);
		pq.push(temp);
	}
	cout << "sort 函數的排列" << endl;
	sort(D.begin(), D.end());
	for (int i = 0; i < 5; i++){
		cout << D[i].x << " " << D[i].y;
		cout << endl;
	}
	cout << "priority_queue 輸出序列" << endl;
	while (!pq.empty()){
		Demo temp = pq.top();
		pq.pop();
		cout << temp.x << " " << temp.y << endl;
	}
	system("pause");
}


同樣是在struct中執行重載< 操作,對於sort是按照x由小到大排序,而priority_queue 是由大到小排列,導致大數先出隊

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