跳到正文

个人记录

priority_queue(优先队列

mengyour约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年11月4日
收录
2025年12月12日
更新
2026年8月17日
篇幅
约 2 分钟

版本

  1. v1当前

优先队列声明的基本格式是:

priority_queue<结构类型> 队列名;

C++
priority_queue <node> q;
//node是一个结构体
//结构体里重载了‘<’小于符号
升序排列
priority_queue <int,vector<int>,greater<int> > q;
降序排列
priority_queue <int,vector<int>,less<int> > q;
//不需要#include<vector>头文件
//注意后面两个“>”不要写在一起,“>>”是右移运算符
priority_queue <int,vector<int>,less<int> >q;

用法:

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

结构体,重载小于

C++
struct node
{
	int x,y;
	bool operator < (const node & a) const
	{
		return x<a.x;
	}
};

或者这样排序

C++
struct cmp{//自定义优先级 
	bool operator()(Node a, Node b){
		if(a.x == b.x) return a.y>b.y; 
		return a.x>b.x; } 
	};

试试效果

C++
#include <bits/stdc++.h>
using namespace std;
struct node
{
    int x,y;
    bool operator < (const node & a) const
    {
        return x>a.x;
    }
};
priority_queue <node> q;
int main(){
	int a;
	for (int i=1;i<=3;i++){
		cin>>a;
		q.push({a,1});
	} 
	for (int i=1;i<=3;i++){
		cout<<q.top().x;
		q.pop();
	}
	return 0;
} 

输出:

C++
cin:3 2 1
cout:1 2 3
原文
抓取于
  1. mengyour

    666