这篇文章主要讲解了“C++中队列queue怎么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++中队列queue怎么用”吧!
queue是一种容器转换器模板,调用#include< queue>即可使用队列类。
queue<Type, Container> (<数据类型,容器类型>)
初始化时必须要有数据类型,容器可省略,省略时则默认为deque 类型
初始化示例
1:
queue<int>q1;
queue<double>q2;
queue<char>q3;
//默认为用deque容器实现的queue;
2:
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() 在队尾插入一个元素
pop() 删除队列第一个元素
size() 返回队列中元素个数
empty() 如果队列空则返回true
front() 返回队列中的第一个元素
back() 返回队列中最后一个元素
2.函数运用示例
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
queue入队,如例:q.push(x); 将x 接到队列的末端。
queue出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
访问queue队首元素,如例:q.front(),即最早被压入队列的元素。
访问queue队尾元素,如例:q.back(),即最后被压入队列的元素。
判断queue队列空,如例:q.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:q.size()
#include <cstdlib>
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int e,n,m;
queue<int> q1;
for(int i=0;i<10;i++)
q1.push(i);
if(!q1.empty())
cout<<"dui lie bu kong\n";
n=q1.size();
cout<<n<<endl;
m=q1.back();
cout<<m<<endl;
for(int j=0;j<n;j++)
{
e=q1.front();
cout<<e<<" ";
q1.pop();
}
cout<<endl;
if(q1.empty())
cout<<"dui lie bu kong\n";
system("PAUSE");
return 0;
}
运行结果:
dui lie bu kong
10
9
0 1 2 3 4 5 6 7 8 9
dui lie bu kong
请按任意键继续. . .
感谢各位的阅读,以上就是“C++中队列queue怎么用”的内容了,经过本文的学习后,相信大家对C++中队列queue怎么用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。