最详细优先队列讲解!

版权声明:未经允许禁止转载。转载请联系我WX:yuyi5453。并且注明出处 https://blog.csdn.net/weixin_40532377/article/details/84939239

来看优先队列的应该都明白队列的含义和基本操作了

优先队列和队列的不同的地方就是优先队列实现自动排序的功能,即优先级高的最先出队。优先级的意思?看看下面就明白了。

1.优先队列的头文件

#include<queue>
//或者#include<bits/stdc++.h>

其中<bits/stdc++.h>是万能头文件,其中包含了C++的所有头文件(最起码我至今没用到不包含的)

2.优先队列的声明

     priority_queue<数据类型> 优先队列名;

priority_queue<int>s;
priority_queue<node>s;//node为结构体,结构体中必须重载 < 运算符

3.优先队列的特性:自动排序

 3.1  对于非结构体队列

   1.优先队列默认是降序(数字越大优先级越高)

int main(){
    priority_queue<int>s;
    s.push(5);
    s.push(3);
    s.push(4);
    
    while(!s.empty()){
        cout<<s.top()<<endl;
        s.pop();
    }
}

输出的结果为5 4 3

2.升序

如果想让数小的优先级高达到升序效果呢?STL提供了 简单的定义方法:priority_queue<int,vector<int>,greater<int> >s;

注意最后两个>不要连起来,有的编译器会当成右移运算符。

int main(){
    priority_queue<int,vector<int>,greater<int> >s;
    s.push(5);
    s.push(3);
    s.push(4);
    
    while(!s.empty()){
        cout<<s.top()<<endl;
        s.pop();
    }
}

输出结果3 4 5

将greater换成less(priority_queue<int,vector<int>,less<int> >s),就是降序,和默认的排序一样。

建议平时怎么写顺手怎么写

3.自定义优先级

如果想使用自定义的优先级怎么办呢?比如让个位数大的优先级更高

可以定义一个用来比较的结构体cmp,重载 “()”运算符,然后用priority_queue<int,vector<int>,cmp>s来定义

重载一定要按格式写!!虽然有的时候不写const不会报错,但是有的时候你就不知道会报什么错。

#include<bits/stdc++.h>
using namespace std;
struct cmp{    //个位数越大优先级越大
	bool operator() (const int a,const int b) const {   //这里b代表优先级较大一方,return后十比较条件    
		return a%10 < b%10;          //a%10 > b%10   则为个位数较小的优先级较大
	}
};
priority_queue<int,vector<int>,cmp>s;
int main(){
    s.push(15);
    s.push(23);
    s.push(34);
    
    while(!s.empty()){
        cout<<s.top()<<endl;
        s.pop();
    }
}
	

输出结果15 35 23

3.2 对于结构体队列

对于结构体队列则需要在结构体中重载运算符来设置优先级。

#include<bits/stdc++.h>
using namespace std;
struct node{
	int x,y;
	bool operator < (const node& a) const{    //x小的优先级高
		return a.x<x;	
	}
};

priority_queue<node>s;
node A;
int main(){
    A.x=5;A.y=3;s.push(A);
    A.x=3;A.y=8;s.push(A);
    A.x=4;A.y=10;s.push(A);
    
    while(!s.empty()){
    	A=s.top();
        printf("(%d,%d)",A.x,A.y);
        s.pop();
    }
}
	

    输出结果:(3,8) (4,10) (5,3)

4.优先队列的使用

s.push();   //入队
s.pop();    //出队
s.top();    //由于最先入队的并不一定是最先出队的所以有点队列的队头是s.top(),而不是s.front()
s.size();   //队列的大小
s.empty();  //队列是否为空

总结一下

关于优先队列的基本内容就这么点,真的是很认真地写了两个小时,从内容到排版,如果有帮到你留个赞谢谢。

猜你喜欢

转载自blog.csdn.net/weixin_40532377/article/details/84939239