STL queue容器
一、定义
queue
是一种容器转换器模板,调用#include< queue>
即可使用队列类。
二、queue初始化
queue<Type, Container>
(<数据类型,容器类型>)
初始化时必须要有数据类型,容器可省略,省略时则默认为deque
类型
初始化示例
queue<int>q1;
queue<double>q2;
queue<char>q3;
//默认为用deque容器实现的queue;
queue<char, list<char>>q1;
//用list容器实现的queue
queue<int, deque<int>>q2;
//用deque容器实现的queue
注意:不能用vector容器初始化queue
因为queue转换器要求容器支持front()、back()、push_back()及 pop_front(),说明queue的数据从容器后端入栈而从前端出栈。所以可以使用deque和list对queue初始化,而vector因其缺少pop_front(),不能用于queue。
三、函数
1.push()在队尾插入一个元素
queue <string> q;
q.push("first");
q.push("second");
cout<<q.front()<<endl;
输出first
2.pop() 将队列中最靠前位置的元素删除,没有返回值
queue <string> q;
q.push("first");
q.push("second");
q.pop();
cout<<q.front()<<endl;
输出 second 因为 first 已经被pop()函数删掉了
3.size() 返回队列中元素个数
queue <string> q;
q.push("first");
q.push("second");
cout<<q.size()<<endl;
输出2,因为队列中有两个元素
4.empty() 如果队列空则返回true
queue <string> q;
cout<<q.empty()<<endl;
q.push("first");
q.push("second");
cout<<q.empty()<<endl;
分别输出1和0
最开始队列为空,返回值为1(ture);
插入两个元素后,队列不为空,返回值为0(false);
5.front() 返回队列中的第一个元素
queue <string> q;
q.push("first");
q.push("second");
cout<<q.front()<<endl;
q.pop();
cout<<q.front()<<endl;
第一行输出first;
第二行输出second,因为pop()已经将first删除了
6.back() 返回队列中最后一个元素
queue <string> q;
q.push("first");
q.push("second");
cout<<q.back()<<endl;
输出最后一个元素second
本文作者:PassName
本文链接:https://www.cnblogs.com/spaceswalker/p/15911289.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步