STL_queue
STL__queue_的應用
 調用的時候要有頭文件: #include<stdlib.h> 或 #include<cstdlib> + #include<queue>?
 詳細用法:
 定義一個queue的變量?????????????????????? queue<Type> que?
 查看是否為空范例????????????????????????????? que.empty()??? 是的話返回1,不是返回0;
 從已有元素后面增加元素(入隊)????? que.push()?
 現有元素的個數????????????????? ?????????????? que.size()
 顯示第一個元素???????????????????????????????? que.front()
 顯示最后一個元素????????????????????????????? que.back()
 清除第一個元素 (出隊)????????????????? que.pop()
 看一個例子:
 
 #include <cstdlib>
 #include <iostream>
 #include <queue>?
 using namespace std;
 int main()
 {?
 ??? queue<int> myQ;
 ??? cout<< "現在 queue 是否 empty? "<< myQ.empty() << endl;?
 ??? cout << "push 5, push 6, push 7" << endl;
 ??? myQ.push(5);?
 ??? myQ.push(6);?
 ??? myQ.push(7);?
 ??? cout << "現在 queue 的元素有幾個? " << myQ.size() << endl;?
 ??? cout << "現在 queue 的front為何? " << myQ.front() << endl;?
 ??? cout << "現在 queue 的rear為何? " << myQ.back() << endl;?
 ??? cout << "pop" << endl; myQ.pop();?
 ??? cout << "現在 queue 的元素有幾個? " << myQ.size() << endl;?
 ??? cout << "現在 queue 的front為何? " << myQ.front() << endl;?
 ??? cout << "現在 queue 的rear為何? " << myQ.back() << endl;?
 ??? system("PAUSE");?
 ??? return 0;
 }
關于隊列的知識;
使用queue之前,要先利用構造函數一個隊列對象,才可以進行元素的入隊,出隊,取隊首和隊尾等操作;
(1)、queue() queue<int> q; 或者 queue<int>Q[10000];
(2)、queue(const queue&) 復制構造函數
例如:用一行代碼利用queue對象q1,創建一個以雙向鏈表為底層容器的queue對象q2
queue<int,list<int>>q1;
queue<int,list<int>>q2(q1);
(3)、元素入隊 函數為:push()例如:q.push(3),意思是將3入隊 ,注意隊列的大小不預設
(4)、元素出隊 函數為:pop()例如:q.pop()
(5)、取對頭元素 函數為:front()
(6)、取隊尾元素 函數為:back()
(7)、判斷對空??? 函數為:empty()
(8)、隊列的大小 函數為:size()返回隊列的當前元素的個數
(9)、如何實現固定大小的queue隊列
在每一次元素入隊列前都判斷當前的隊列是否滿,用雙向鏈表做queue 的底層容器可以實現
例如:
 #include<iostream>
 #include<list>
 #include<queue>
 using namespace std;
 #define QUEUE_SIZE 50 //固定大小;
 int main()
 {
 queue<int,list<int>> q;
 if(q.size(QUEUE_SIZE) )
 ?? q.push(51);
 if(q.size(QUEUE_SIZE) )
 ?? q.push(36);
 if(q.size(QUEUE_SIZE))
 ?? q.push(28);
 while(!q.empty() )
 {
 ?? cout<<q.front()<<endl;
 ?? q.pop();
 }
 return 0;
 }
 
 #include<iostream>
 #include<cstdio>
 #include<queue>
 #include<stdlib>
 using namespace std;
 int main()
 {
 register int i,j;
 int m,n;
 char c[6];
 int x,y;
 while(scanf("%d %d",&n,&m)!=EOF)
 {
 ?? queue<int> Q[10000];
 ?? for(i=1;i<m;i++)
 ?? {
 ??? scanf("%s",&c);
 ??? if(strcmp(c,"INT") == 0)
 ??? {
 ???? for(j=1;j<=n;j++)
 ???? {
 ????? while(!Q[j].empty())
 ????? {
 ?????? Q[j].pop();
 ????? }
 ????? continue;
 ???? }
 ??? }
 ??? if(strcmp(c,"PUSH")==0)
 ??? {
 ???? scanf("%d %d",&x,&y);
 ???? Q[x].push(y);
 ???? continue;
 ??? }
 ??? if(strcmp(c,"POP")==0)
 ??? {
 ???? scanf("%d ",&y);
 ???? if(Q[y].empty)
 ???? {
 ????? printf("NULL\n");continue;
 ???? }
 ???? else
 ???? {
 ????? printf("%d\n",Q[y].front());
 ???? }
 ???? Q[y].pop;
 ??? }
 ?? }
 }
 return 0;
 }
總結