C++队列queue

只能访问 queue<T> 容器适配器的第一个和最后一个元素。只能在容器的末尾添加新元素,只能从头部移除元素。

许多程序都使用了 queue 容器。queue 容器可以用来表示超市的结账队列或服务器上等待执行的数据库事务队列。对于任何需要用 FIFO 准则处理的序列来说,使用 queue 容器适配器都是好的选择。

调用#include< 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 
 

queue 的生成方式和 stack 相同,下面展示如何创建一个保存字符串对象的

std::queue<std::string> words;

也可以使用拷贝构造函数:std::queue<std::string> copy_words {words}; // A duplicate of words

stack<T>、queue<T> 这类适配器类都默认封装了一个 deque<T> 容器,也可以通过指定第二个模板类型参数来使用其他类型的容器:std::queue<std::string, std::list<std::string>>words;

底层容器必须提供这些操作:front()、back()、push_back()、pop_front()、empty() 和 size()。

注意:不能用vector容器初始化queue
因为queue转换器要求容器支持front()、back()、push_back()及 pop_front(),说明queue的数据从容器后端入栈而从前端出栈。所以可以使用deque和list对queue初始化,而vector因其缺少pop_front(),不能用于queue。

二、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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值