STL学习笔记6 -- 栈stack 、队列queue 和优先级priority_queue 三者比较
栈stack 、队列queue 和优先级priority_queue 三者比较
默认下stack 和queue 基于deque 容器实现,priority_queue 则基于vector 容器实现。
stack 先进后出
queue 先进先出
priority_queue 按优先级出队
代码示例如下:
1 #include "iostream" 2 using namespace std; 3 #include "string" 4 #include "stack" 5 #include "queue" 6 7 int main() 8 { 9 //first in last out 10 stack <int> stack1; 11 stack1.push(12); 12 stack1.push(145); 13 stack1.push(233); 14 cout<<"pop:"<<stack1.top()<<endl;//取得栈顶元素233 15 stack1.pop();//移除元素 16 if (stack1.empty()) 17 { 18 cout<<"The stack is empty!"<<endl; 19 } 20 cout<<"元素个数"<<stack1.size()<<endl; 21 cout<<"**************************************"<<endl; 22 ////////////////////////////////////////////////////////////////////////// 23 //first in first out 24 queue <int> queue1; 25 queue1.push(111); 26 queue1.push(222); 27 queue1.push(333); 28 cout<<"font:"<<queue1.front()<<endl;//111 29 cout<<"back:"<<queue1.back()<<endl;//333 30 if (queue1.empty()) 31 { 32 cout<<"The queue is empty!"<<endl; 33 } 34 cout<<"元素个数"<<queue1.size()<<endl; 35 cout<<"**************************************"<<endl; 36 ////////////////////////////////////////////////////////////////////////// 37 // Priority Queues(优先队列),从大到小 38 priority_queue <string> queue2; 39 queue2.push("aaaa"); 40 queue2.push("dddd"); 41 queue2.push("cccc"); 42 cout<<"top:"<<queue2.top()<<endl;//结果是dddd 43 if (queue2.empty()) 44 { 45 cout<<"The queue is empty!"<<endl; 46 } 47 cout<<"元素个数"<<queue2.size()<<endl; 48 cout<<"**************************************"<<endl; 49 50 getchar(); 51 return 0; 52 }
本文来自博客园,作者:struggle_time,转载请注明原文链接:https://www.cnblogs.com/songliquan/p/3341288.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?