优先队列与普通队列的差别在于,普通队列是按照先入队先出队的顺序,而优先队列则是以优先级的大小顺序进行出队。通常情况下,我们会默认有大优先级的元素排在队头,即为大根堆;相反,如果最大优先级的元素在队尾,则被称为小根堆。

基础操作

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	priority_queue<int> maxq;//创建大根堆 
	maxq.push(10);
	maxq.push(2);
	maxq.push(4);//添加元素
	cout<<maxq.size()<<endl;//输出队长
	cout<<maxq.top()<<endl;//输出队首
	maxq.pop();//弹出队首
	cout<<maxq.top()<<endl;//输出弹出队首后的元素
	maxq.push(29);
	while(maxq.size()){
		cout<<maxq.top()<<" ";
		maxq.pop();
	}//遍历 
	
	return 0;
}

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	priority_queue<int,vector<int >,greater<int >> minq;//创建小根堆 
	minq.push(10);
	minq.push(2);
	minq.push(4);//添加元素
	cout<<minq.size()<<endl;//输出队长
	cout<<minq.top()<<endl;//输出队首
	minq.pop();//弹出队首
	cout<<minq.top()<<endl;//输出弹出队首后的元素
	minq.push(29);
	while(minq.size()){
		cout<<minq.top()<<" ";
		minq.pop();
	}//遍历 
	return 0;
}

结构体自定义优先级

在上述代码中,我们实现优先级是优先队列默认通过元素大小判断优先级。但在实际情况中,我们通常需要通过自定义的方式进行优先级大小判断。于是我们需要重构小于运算符号<来实现我们的目的。

例如在登记学生的成绩中,为了实现以下要求 :

  • 高分排在前面;
  • 同等分数,语文高排在前面;
  • 相同语文,数学高排在前面;

则可通过以下方式:

#include<iostream>
#include<queue>
using namespace std;
struct Student{
	string name;
	int zf,yf,sf;
	bool operator<(const Student &a) const {
		if(zf!=a.zf)return zf<a.zf;
		if(yf!=a.yf)return yf<a.yf;
		return sf<a.sf;
	} 
};
int main()
{
	priority_queue<Student> q;
	q.push(Student{"xiaom",100,50,50});
    q.push(Student{"xiaoh",90,40,50});
    q.push(Student{"xiaoj",90,20,70});
    while(!q.empty()){
    	cout<<q.top().name<<endl;
    	q.pop();
	}
	return 0;
}

更多推荐