数据结构:优先队列

定义

普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。

在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。通常采用堆数据结构来实现。

和队列基本操作相同:

top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容

C++

特性:自动排序

  1. 自动排序:降序
#include<cstdio>
#include<queue>
using namespace std;
priority_queue <int> q;
int main()
{
	q.push(10),q.push(8),q.push(12),q.push(14),q.push(6);
	while(!q.empty())
		printf("%d ",q.top()),q.pop();
}

程序大意就是在这个优先队列里依次插入10、8、12、14、6,再输出。

结果: 14 12 10 8 6
也就是说,它是按从大到小排序的!

  1. 默认的优先队列(结构体,重载小于)
    先看看这个结构体是什么。
struct node
{
	int x,y;
	bool operator < (const node & a) const
	{
		return x<a.x;
	}
};
  • 它也是按照重载后的小于规则,从大到小排序的。在c++中,小于规则是升序,但对于这里的优先队列,反而是降序!!!
  1. less和greater优先队列
    还是以int为例,先来声明:
//第一个参数int是存储的元素的数据类型;第二个参数是队列中存储的元素类型是vector,第三个参数less/greater是定义队列的排序规则
priority_queue <int,vector<int>,less<int> > p;
priority_queue <int,vector<int>,greater<int> > q;

程序和结果:

#include<cstdio>
#include<queue>
using namespace std;
priority_queue <int,vector<int>,less<int> > p;
priority_queue <int,vector<int>,greater<int> > q;
int a[5]={10,12,14,6,8};
int main()
{
	for(int i=0;i<5;i++)
		p.push(a[i]),q.push(a[i]);
		
	printf("less<int>:");
	while(!p.empty())
		printf("%d ",p.top()),p.pop();	
		
	printf("\ngreater<int>:");
	while(!q.empty())
		printf("%d ",q.top()),q.pop();
}

结果:
less:14 12 10 8 6
greater:6 8 10 12 14

  • 所以,我们可以知道,less是从大到小,greater是从小到大。

C++更多使用
详细定义和使用

posted @ 2022-04-09 12:30  CodeWater  阅读(130)  评论(0编辑  收藏  举报