queue&priority_queue&deque的应用

queue和priority_queue都是引用#include<queue>头文件,deque引用#include<deque>头文件

queue

定义:queue<T>pq;

方法 描述

示例

时间复杂度
push 入队(从队尾) pq.push(element) O(1)
pop 出队(从队头) pq.pop() O(1)
front 队头元素 int x=pq.front() O(1)
back 队尾元素 int y=pq.back() O(1)

priority_queue

定义:priority_queue<T>pq;

方法 描述 示例 时间复杂度
push 把元素插入堆 pq.push(k) O(log n)
pop 删除堆顶元素 pq.pop() O(log n)
top 查询堆顶元素(最大值) int k=pq.top() O(1)

priority_queue的重载<运算符

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 struct node{
 5     int x,y;
 6     bool operator<(const node&b)const{
 7         if(x==b.x){
 8             return y>=b.y;
 9         }else{
10             return x>b.x;
11         } 
12     }
13 };
14 priority_queue<node>pq;
15 int main(){
16     for(int i=1;i<=5;i++){
17         for(int j=1;j<=5;j++){
18             pq.push(node{i,j});
19         }
20     } 
21     while(!pq.empty()){
22         cout<<pq.top().x<<" "<<pq.top().y<<endl;
23         pq.pop();
24     }
25     return 0;
26 }

 

deque

它是双向队列

定义:deque<T>pq;

方法 描述 示例 时间复杂度
[] 随机访问 与vector类似 O(1)
begin/end deque的头/尾迭代器 与vector迭代器类似 O(1)
front/back 队头/尾元素 与queue类似 O(1)
push_back 从队尾入队 pq.push_back(k) O(1)
push_front 从队头入队 pq.push_front(k) O(1)
pop_front 从队头出队 pq.pop_front() O(1)
pop_back 从队尾出队 pq.pop_back() O(1)
clear 清空队列 pq.clear() O(1)

猜你喜欢

转载自www.cnblogs.com/hazel-wu/p/11279999.html
今日推荐