C++进阶-3-4stack容器、queue容器
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 //
浙公网安备 33010602011771号