C++ 提高程式設計 queue容器
阿新 • • 發佈:2021-09-27
#include <queue> #include <string> class Person { public: Person(string name, int age) { this->m_Name = name; this->m_Age = age; } string m_Name; int m_Age; }; void test01() { //建立佇列 queue<Person> q; //準備資料 Person p1("唐僧", 30); Person p2("孫悟空", 1000); Person p3("豬八戒", 900); Person p4("沙僧", 800); //向佇列中新增元素 入隊操作 q.push(p1); q.push(p2); q.push(p3); q.push(p4); //佇列不提供迭代器,更不支援隨機訪問 while (!q.empty()) { //輸出隊頭元素 cout << "隊頭元素-- 姓名: " << q.front().m_Name << " 年齡:"<< q.front().m_Age << endl; cout << "隊尾元素-- 姓名: " << q.back().m_Name << " 年齡: " << q.back().m_Age << endl; cout << endl; //彈出隊頭元素 q.pop(); } cout << "佇列大小為:" << q.size() << endl; }int main() { test01(); system("pause"); return 0; }