sort 及 priority_queu 中struct结构体的重载<排序

这篇博客探讨了在STL中,struct结构体中自定义的重载<操作如何影响sort和priority_queue的行为。sort会按x从小到大排序,而priority_queue则相反,从大到小排列,导致priority_queue的大数优先出队。
摘要由CSDN通过智能技术生成

关于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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值