跳到正文

个人记录

priority_queue

GKE心林电约 5 分钟
原文
文章信息与版本

文章信息

发布
2018年8月11日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 5 分钟
获赞
1

版本

  1. v1当前

优先队列是一种队列排程序(不是方法),具体操作如下

首先声明一个优先队列

priority_queue<结构类型> 队列名;

之后这个队列就会进行排序

然后是这个队列的几种操作

C++
	q.size();//返回q里元素个数
	q.empty();//返回q是否为空,空则返回1,否则返回0
	q.push(k);//在q的末尾插入k
	q.pop();//删掉q的第一个元素
	q.top();//返回q的第一个元素
    q为队列名

打一个演示

C++
#include<bits/stdc++.h>
using namespace std;
priority_queue <int> i;
int main()
{ 
	//i:q.push(k)演示 
	i.push(1); 
	i.push(4);
	i.push(2);
	i.push(3);
	i.push(5);
	//展示队列元素(先搞懂队列中是什么情况,之后演示操作),
	while(!i.empty())
        printf("%d ",i.top()),i.pop();
	return 0;
}

可看出,队列中元素自动排序(降序)

然后打上具体操作

C++
#include<bits/stdc++.h>
using namespace std;
priority_queue <int> i;
int main()
{
	//i:q.push(k)演示 
	i.push(5); 
	i.push(4);
	i.push(2);
	i.push(3);
	i.push(1);
	//i:q.size()演示
	cout<<"队列i中元素的个数是:"<<i.size()<<endl;
	//q.top()演示
	int st=i.top();
	cout<<"队头为:"<<st<<endl; 
	//q.pop()演示
	i.pop();
	cout<<"pop一次后队列i中元素的个数是:"<<i.size()<<endl;
	//q.empty()演示
	while(!i.empty())
	{
		i.pop();
		cout<<"剩余元素的个数是:"<<i.size()<<endl;
	}
	return 0;
}

之后是两个优先队列

C++
priority_queue <int,vector<int>,less<int> > p;
priority_queue <int,vector<int>,greater<int> > q;

这里要注意两个”>“不能打在一起,中间需要空格

具体演示为

C++
#include<bits/stdc++.h>
using namespace std;
priority_queue <int,vector<int>,less<int> > p;//降序
priority_queue <int,vector<int>,greater<int> > q;//升序
int main()
{  
	p.push(1); 
	p.push(4);
	p.push(2);
	p.push(3);
	p.push(5);
	q.push(1); 
	q.push(4);
	q.push(2);
	q.push(3);
	q.push(5);
	printf("less:");
	while(!p.empty())
        printf("%d ",p.top()),p.pop();
    printf("\n");
    printf("greater:");
    while(!q.empty())
        printf("%d ",q.top()),q.pop();
	return 0;
}

之后是结构体操作

首先声明

priority_queue <结构体名> 队列名;

然后是具体操作

C++
#include<bits/stdc++.h>
using namespace std;
struct yanshi{
	int x,y;
	bool operator < (const yanshi &a) const//重载运算符 
	{
		return x<a.x;//关于x的降序 
	}
	/*bool operator < (const yanshi &a) const//重载运算符 
	{
		return x>a.x;//关于x的升序,注意上面的"<"不改变,因为是自动降序,只需重载"<"; 
	}*/
}s;
priority_queue <yanshi> q;
int main()
{
	s.x=10,s.y=100; q.push(s);
    s.x=12,s.y=60; q.push(s);
    s.x=14,s.y=40; q.push(s);
    s.x=6,s.y=80; q.push(s);
    s.x=8,s.y=20; q.push(s);
    while(!q.empty())
    {
        yanshi m=q.top(); 
        printf("(%d,%d)\n",m.x,m.y);
        q.pop();
    }
}

根据某一特定值排序

C++
#include<bits/stdc++.h>
using namespace std;
int a[15];
struct cmp{
    bool operator () (int x,int y)
    {
    	return a[x]<a[y];//这里是降序! 
	}
};
priority_queue<int,vector<int>,cmp> q;
int main()
{
    for(int i=1;i<=10;++i)
    a[i]=i;
    for(int i=10;i>=1;--i)
    q.push(i);
    while(!q.empty())
    {
    	printf("%d\n",a[q.top()]);
    	q.pop();
	}
    return 0;
}
原文