C++進階-3-4stack容器、queue容器
1 #include<iostream> 2 #include<stack> 3 #include<queue> 4 using namespace std; 5 6 // stack 容器 7 // 先進后出 8 9 // queue 容器 10 // 先進先出 11 12 // stack 容器 13 void test01() { 14 15 stack<int>s; 16 17 // 入堆疊 18 s.push(10); 19 s.push(20); 20 s.push(30); 21 s.push(40); 22 23 cout << "堆疊的大小:" << s.size() << endl; 24 25 // 只要堆疊不為空,查看堆疊頂,并且執行出堆疊操作 26 while (!s.empty()) 27 { 28 // 查看堆疊頂元素 29 cout << "堆疊頂元素為:" << s.top() << endl; 30 31 // 出堆疊 32 s.pop(); 33 } 34 cout << "堆疊的大小:" << s.size() << endl; 35 36 } 37 38 39 // queue 容器 40 41 class Person { 42 43 public: 44 Person(string name, int age) { 45 this->m_Name = name; 46 this->m_Age = age; 47 } 48 string m_Name; 49 int m_Age; 50 }; 51 52 void test02() { 53 54 // 創建佇列 55 queue<Person>q; 56 57 // 準備資料 58 Person p1("唐僧", 30); 59 Person p2("孫悟空", 45); 60 Person p3("豬八戒", 60); 61 Person p4("沙悟凈", 10); 62 63 // 入隊 64 q.push(p1); 65 q.push(p2); 66 q.push(p3); 67 q.push(p4); 68 69 cout << "佇列大小為:" << q.size() << endl; 70 71 // 判斷只要佇列不為空,查看隊頭,查看隊尾 72 while (!q.empty()) 73 { 74 // 查看隊頭 75 cout << "隊頭元素 --- 姓名:" << q.front().m_Name << " 年齡:" << q.front().m_Age << endl; 76 77 // 查看隊尾 78 cout << "隊頭元素 --- 姓名:" << q.back().m_Name << " 年齡:" << q.back().m_Age << endl; 79 80 // 出隊 81 q.pop(); 82 } 83 84 cout << "佇列大小為:" << q.size() << endl; 85 86 } 87 88 int main() { 89 90 // stack容器 91 //test01(); 92 93 // queue容器 94 test02(); 95 96 system("pause"); 97 98 return 0; 99 } 100 101 // 總結 102 // 103 // stack容器 104 // 105 // 概念:stack是一種先進后出(First In Last Out,FILO)的資料結構,他只有一個出口 106 // 107 // 堆疊中只有頂端元素才可以被外界使用,因此堆疊不允許有遍歷行為 108 // 109 // stack不允許有遍歷行為 110 // 111 // 112 // 113 // queue 容器 114 // 115 // 概念:queue是一種先進先出(First In First Out,FIFO)的資料結構,它有兩個出口 116 // 117 // queue不允許有遍歷行為 118 //
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469921.html
標籤:其他
上一篇:資料轉發程序
