- 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/285773.html
標籤:其他
下一篇:Unity的asm筆記
