STL:雙端佇列
阿新 • • 發佈:2019-01-29
雙端佇列是STL中queue的“高階版”,一般佇列只支援從一個方向“先進後出”,而雙端佇列deque支援從兩個方向插入和彈出元素
定義:
#include <queue>
using namespace std;
int main()
{
deque<int> a;
return 0;
}
當然這裡的int可以換成其他型別,double、long、char、string、甚至是自定義型別。
操作:
(由於時間有限,只寫出與競賽有關的操作)
#include <queue>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
deque<int> dq; //定義佇列
dq.clear(); //清空佇列
dq.push_back(1); //從尾部插入元素“1”
dq.push_front(4); //從頭部插入元素“4”
printf("%d\n",dq.size()); //返回佇列元素個數
printf("%d\n",dq.front()); //返回佇列首部元素
printf("%d\n",dq.back()); //返回佇列尾部元素
deque<int>::iterator it=dq.begin(); //定義迭代器
for (it=dq.begin();it!=dq.end();it++) //依次遍歷輸出
printf("%d\n",*it);
dq.pop_back(); //彈出隊尾元素
printf("%d\n",dq.back());
dq.pop_front(); //彈出隊首元素
if (dq.empty()) printf("The queue is empty! %d \n",dq.size()); //檢查佇列是否為空
system("pause");
return 0;
}
輸出結果:
值得一提的是,deque也可以像陣列一樣,通過dq[i]這種形式,訪問元素。
效率:
deque在首尾插入等操作方面是幾乎不耗時的,但初始化就不一定了:據說有人測過n=10^6時要0.3秒? 還有沒介紹的中間插入和刪除,如果你用了,那麼卡個評測機幾分鐘應該是沒問題的……(原理就像vector,中間插入需要移動大量元素)
所以,還是那句話:能不用STL儘量別用,還是老老實實開陣列或者用vector吧……