• queue的定義
queue<typename> name; 
  • queue容器內元素的訪問

  由於佇列本身就是一種先進先出的限制性資料結構,因此在STL中只能通過front()來訪問隊首元素,或是通過back()來訪問隊尾元素。

示例:

 1 #include <iostream>
2 #include <queue>
3 using namespace std;
4 queue<int> q;
5 int main()
6 {
7 for(int i=0;i<5;i++){
8 q.push(i+1); //push將i+1壓入佇列
9 }
10 cout<<q.front()<<" "<<q.back();
11 return 0;
12 }
輸出結果:
1 5
  • queue常用函式

  (1)push()

  push(x)將x進入佇列,時間複雜度為O(1)。

  (2)front()、back()

  front()和back()可以分別獲得隊首元素和隊尾元素,時間複雜度為O(1)。

  (3)pop()

  pop()令隊首元素出隊,時間複雜度為O(1)。

示例:

 1 #include <iostream>
2 #include <queue>
3 using namespace std;
4 queue<int> q;
5 int main()
6 {
7 for(int i=0;i<5;i++){
8 q.push(i+1); //push將i+1壓入佇列
9 }
10 for(int i=0;i<2;i++){
11 q.pop(); //出隊2次(1,2出隊)
12 }
13 cout<<q.front();
14 return 0;
15 }
輸出結果:
3

  (4)empty()

  empty()檢測queue是否為空,返回true為空,返回false為非空。時間複雜度為O(1)。

示例:

 1 #include <iostream>
2 #include <queue>
3 using namespace std;
4 queue<int> q;
5 int main()
6 {
7 if(q.empty()==true){ //初始時,佇列為空
8 cout<<"empty"<<endl;
9 }
10 else{
11 cout<<"not empty"<<endl;
12 }
13 q.push(1); //在入隊1後,佇列非空
14 if(q.empty()==true){
15 cout<<"empty"<<endl;
16 }
17 else{
18 cout<<"not empty"<<endl;
19 }
20 return 0;
21 }
輸出結果:
empty
not empty

  (5)size()

  size()返回queue內元素的個數,時間複雜度為O(1)。

示例:

 1 #include <iostream>
2 #include <queue>
3 using namespace std;
4 queue<int> q;
5 int main()
6 {
7 for(int i=0;i<5;i++){
8 q.push(i+1); //push將i+1壓入佇列
9 }
10 cout<<q.size();
11 return 0;
12 }
輸出結果:
5