1. 程式人生 > 實用技巧 >c++queue容器

c++queue容器

queue 模板類的定義在<queue>標頭檔案中。
與stack 模板類很相似,queue 模板類也需要兩個模板引數,一個是元素型別,一個容器類
型,元素型別是必要的,容器型別是可選的,預設為deque 型別。
定義queue 物件的示例程式碼如下:
queue<int> q1;
queue<double> q2;

queue 的基本操作有:
入隊,如例:q.push(x); 將x 接到佇列的末端。
出隊,如例:q.pop(); 彈出佇列的第一個元素,注意,並不會返回被彈出元素的值。
訪問隊首元素,如例:q.front(),即最早被壓入佇列的元素。
訪問隊尾元素,如例:q.back(),即最後被壓入佇列的元素。
判斷佇列空,如例:q.empty(),當佇列空時,返回true。
訪問佇列中的元素個數,如例:q.size()

 1 #include<iostream>
 2 using namespace std;
 3 #include<queue>
 4 #include<algorithm>
 5 
 6 //佇列中基本資料模型
 7 void main61()
 8 {
 9     queue<int> q;
10     q.push(1);
11     q.push(2);
12     q.push(3);
13     q.push(4);
14 
15 
16     cout << "隊頭元素:" << q.front() << endl;
17 cout << "佇列大小:" << q.size() << endl; 18 19 while (!q.empty()) 20 { 21 cout << q.front() << " "; 22 q.pop(); 23 24 } 25 } 26 27 //佇列的演算法 和 資料型別的分離 28 class Teacher 29 { 30 public: 31 int age; 32 char name[32]; 33 34 public: 35 void
printT() 36 { 37 cout << "age: " << age << endl; 38 } 39 }; 40 //佇列中物件資料模型 41 void main62() 42 { 43 Teacher t1, t2, t3; 44 t1.age = 31; 45 t2.age = 32; 46 t3.age = 33; 47 queue<Teacher> q; 48 q.push(t1); 49 q.push(t2); 50 q.push(t3); 51 52 while (!q.empty()) 53 { 54 Teacher temp = q.front(); 55 temp.printT(); 56 q.pop(); 57 } 58 59 60 61 } 62 //佇列中指標資料模型 63 void main63() 64 { 65 Teacher t1, t2, t3; 66 t1.age = 31; 67 t2.age = 32; 68 t3.age = 33; 69 queue<Teacher *> q; 70 q.push(&t1); 71 q.push(&t2); 72 q.push(&t3); 73 74 while (!q.empty()) 75 { 76 Teacher *temp = q.front(); 77 temp->printT(); 78 q.pop(); 79 } 80 81 82 83 } 84 int main() 85 { 86 main63(); 87 88 89 90 system("pause"); 91 return 0; 92 }