队列以及优先队列

1.队列

队列的定义:

头文件#include<queue>

队列是一种先进先出的数据结构

队列的声明

queue<char> q;  //声明字符类型

queue<node > q;  //声明结构体类型

...........

以及可以声明一些自定义的类型

队列的操作

入队列   s.push(x);

出队列   s.pop();

返回队列的数据数量  s.size();

判断队列是否为空   s.empty();  如果为空队列返回为true

返回队列头部元素  q.front();

返回队列尾部元素  q.back();

2.优先队列

#include<stdio.h>
#include<iostream>
#include<queue>
#include<algorithm> 
using namespace std;
struct cmp1
{
    bool operator ()(int &a,int &b)
    {
        return a>b;//最小值优先
    }
};
struct cmp2
{
    bool operator ()(int &a,int &b)
    {
        return a<b;//最大值优先
    }
};
int main()
{
    priority_queue<int,vector<int>,cmp1> que1;            //自定义,小值优先 
    priority_queue<int,vector<int>,cmp2> que2;            //自定义,大值优先 
    priority_queue<int,vector<int>,greater<int> > que3;   //调函数,小值优先
    priority_queue<int,vector<int>,less<int> > que4;      //调函数,大值优先
    
    int n,a;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){  
        cin>>a;
        que1.push(a);
        que2.push(a);
        que3.push(a);
        que4.push(a);
    }                //例如样例输入为:   5 7 3 8 4 1
    
    while(!que1.empty())
    {
        cout<<que1.top()<<endl;
        que1.pop();
    }               //que1排列后输出为:  1 3 4 5 7 8 
    cout<<endl;
    
    while(!que2.empty())
    {
        cout<<que2.top()<<endl;
        que2.pop();
    }              //que2排列后输出为:   8 7 5 4 3 1
    cout<<endl;
    
    while(!que3.empty())
    {
        cout<<que3.top()<<endl;
        que3.pop();
    }              //que3排列后输出为:  1 3 4 5 7 8
    cout<<endl;
    
    while(!que4.empty())
    {
        cout<<que4.top()<<endl;
        que4.pop();
    }              //que4排列后输出为:  8 7 5 4 3 1
    cout<<endl;
    
    return 0;
}

看到样例代码即可知,使用优先队列,默认从大到小的排序,优先队列里面的函数可以直接调用

也可以自定义编写代入以改变队列的优先性。

同时可以看出优先队列取值的时候只能使用q.top(),来取队列的头元素。使用q.pop(),来删除头元素

 priority_queue<int,vector<int>,cmp1> que1;            //自定义,小值优先 
    priority_queue<int,vector<int>,cmp2> que2;            //自定义,大值优先 
    priority_queue<int,vector<int>,greater<int> > que3;   //调函数,小值优先
    priority_queue<int,vector<int>,less<int> > que4;      //调函数,大值优先
    

所调用的函数有

struct cmp1
{
    bool operator ()(int &a,int &b)
    {
        return a>b;//最小值优先
    }
};
struct cmp2
{
    bool operator ()(int &a,int &b)
    {
        return a<b;//最大值优先
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值