二、#include < queue >
头文件queue主要包含循环队列queue和优先队列priority_queue两个容器。
-
queue:
- push(x): 把x元素入队。O(1)
- pop(): 出队(从队头),从队列中删除。O(1)
- front(): 返回队头元素。O(1)
-
. priority_queue
-
push(x): 把x元素入堆。O(log n)
-
pop(): 删除堆顶元素。O(log n)
-
top():查询堆顶元素(最大值)O(1)
priority_queue可理解为一个大根二叉堆。
priority_queue中存储的元素类型必须定义“小于号”,较大的元素会放在队列前面,内置的int, string等类型本身就可以比较大小。若使用结构体类型,则需要重载 “<"运算符。
-
代码:
#include <queue>
#include <cstdio>
#include <iostream>
using namespace std;
struct node {
int x;
node(int xx) {
x = xx;
}
friend bool operator <(node a, node b) {
return a.x > b.x; //转化为以x小的出队 ]
//重载了<符号。 这样priority_queue就会认为“大"的更”小“,”小“的更"大",从而x较小的元素会被放在堆顶。
}
};
int main() {
queue<int> a;
a.push(1);
a.push(2);
a.push(3);
//一个一个出队 先进先出
while (a.size()) {
//a.front() 返回队头第一个元素,但是不在队里删除
printf("%d ", a.front());
//pop()函数将队头元素出队
a.pop();
}
printf("\n");
//优先队列 priority_queue 那个元素优先,那个元素就先出队, int默认大的先出队
priority_queue<int> b;
b.push(1);
b.push(2);
b.push(3);
while (b.size()) {
//b.top() 查询堆顶元素
printf("%d ", b.top());
b.pop();
}
printf("\n");
priority_queue<node> c;
c.push(node(3));
c.push(node(6));
c.push(node(10));
while (c.size()) {
printf("%d ", c.top().x);
c.pop();
}
return 0;
}