一、 头文件
#include<queue>
二、队列的声明
- queue< int >q; //队列q中存 int 型元素
- queue< double >q; //q中存 double 型元素
- queue< node >q; //q中存结构体
- ……
三、对队列的操作
- q.push(k); //在队尾插入k
- q.front(); //返回q的第一个元素
- q.pop(); //q的第一个元素出队列
- q.empty(); //q为空则返回1 , 反之为0
- q.back(); //返回q的末尾元素
- 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