优先队列的比较函数为什么要让他return false啊?
  • 板块学术版
  • 楼主Konjac0629
  • 当前回复3
  • 已保存回复3
  • 发布时间2021/8/18 11:20
  • 上次更新2023/11/4 10:14:02
查看原帖
优先队列的比较函数为什么要让他return false啊?
553640
Konjac0629楼主2021/8/18 11:20

蒟蒻在看P1427题解的时候
看到第一个大佬介绍了一种用优先队列实现的方法
他这里的比较函数为什么要让他return false啊(即为什么要return x.time<y.time而不是return x.time>y.time)

#include<iostream>
#include<queue>//优先队列的头文件,它还含有另一种数据结构:队列--queue 
using namespace std;
struct node{
	int time;
	int value; 
}t;
priority_queue<node> a;
bool operator<(const node &x,const node &y){//这里比较函数的名字不能改,两个const和两个&也不能去掉
	return x.time<y.time;
}//定义优先队列的比较函数,这个和sort相反,是使得排序后前后代入可以return false,具体细节请自行了解吧
int c,n;
int main(){
	while(1){
		cin>>c;
		if(c==0) break;
		n++;
		t.value=c;
		t.time=n;
		a.push(t);//将元素输入优先队列 
	}
	while(!a.empty()){
		cout<<a.top().value<<" ";//.top()返回	   优先队列的第一个元素
		a.pop();//删除优先队列的第一个元素 
	}
	return 0;
} 
2021/8/18 11:20
加载中...