队列

一、 头文件

#include<queue>

二、队列的声明

  1. queue< int >q; //队列q中存 int 型元素
  2. queue< double >q; //q中存 double 型元素
  3. queue< node >q; //q中存结构体
  4. ……

三、对队列的操作

  1. q.push(k); //在队尾插入k
  2. q.front(); //返回q的第一个元素
  3. q.pop(); //q的第一个元素出队列
  4. q.empty(); //q为空则返回1 , 反之为0
  5. q.back(); //返回q的末尾元素
  6. q.size(); //返回q中元素的个数
  • 例:
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
int main()
{
    queue<int>q;
    q.push(2);
    q.push(88);
    q.push(1);
    q.push(46);
    q.push(-1);
    while(!q.empty())
    {
        cout << q.front() <<" ";
        q.pop();
    }
}

  • 结果
2 88 1 46 -1

四、队列类型

1.优先队列(自动排序)

优先队列中 没有 q.back()
返回队列中第一个元素的是 q.top(), 不是q.front().

什么是优先队列

普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。

声明

 priority_queue<int>q;           //q中元素自动排序为从大到小
 priority_queue<int,vector<int>,less<int> > q; //q中元素自动排序为从大到小
 priority_queue<int,vector<int>,greater<int> > q; //q中元素自动排序为从小到大

注意 : > > 两个符号不能连着写
less 从大到小,greater从小到大

#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;

int main()
{
    priority_queue<int>q;   //与声明成priority_queue<int,vector<int>,less<int> > q 功能一样
    q.push(2);q.push(88);q.push(1);q.push(46);q.push(-1);
    while(!q.empty())
    {
        cout << q.top() <<" ";
        q.pop();
    }
}

  • 结果
    88 46 2 1 -1

#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> > q;
    q.push(2);q.push(88);q.push(1);q.push(46);q.push(-1);
    while(!q.empty())
    {
        cout << q.top() <<" ";
        q.pop();
    }
}
  • 结果
    -1 1 2 46 88
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值