c++ queue 的使用

目录

1. 默认构造函数

2. void push(const T& x) 

3. void pop() 

4. T& front()

5. T& back() 

6.  bool empty()

7. size_t size()


下面是 queue 的简介,来自 queue - C++ Reference (cplusplus.com)

 的中文翻译,看看就行了,没必要深究,最终我们都会在模拟实现的时候讲解清楚的!

1. 队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元素,另一端 提取元素。

2. 队列作为容器适配器实现,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的 成员函数来访问其元素。元素从队尾入队列,从队头出队列。

3. 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少支持以下操 作: empty:检测队列是否为空 size:返回队列中有效元素的个数 front:返回队头元素的引用 back:返回队尾元素的引用 push_back:在队列尾部入队列 pop_front:在队列头部出队列

4. 标准容器类deque和list满足了这些要求。默认情况下,如果没有为queue实例化指定容器类,则使用标 准容器deque。

1. 默认构造函数

这是 queue 的使用中用得最多的构造函数,当然 queue 肯定有拷贝构造函数撒!

下面的代码演示了如何创建一个 queue。

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	queue < int> q;

	return 0;
}

2. void push(const T& x) 

这个函数可以向队列中加入一个元素!我们都知道 queue 是一种数据结构,他的特点是:只允许在队头 (front) 出数据,只允许在队尾 (back) 入数据。符合先进先出的特点!

下面的代码演示如何使用 queue 插入数据:

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	queue < int> q;

	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);

	return 0;
}

3. void pop() 

这个函数可以删除队列中的一个元素,根据队列的特性,删除的是队头 (front) 的元素。

 

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	queue < int> q;

	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);

	q.pop();

	return 0;
}

4. T& front()

查看队头的数据。

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	queue < int> q;

	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);

	cout << q.front() << endl; // 输出:1

	return 0;
}

5. T& back() 

查看队尾的数据。

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	queue < int> q;

	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);

	cout << q.back() << endl; // 输出:4

	return 0;
}

6.  bool empty()

判断队列是否为空。

7. size_t size()

获取队列的大小。

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	queue < int> q;

	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);

	cout << q.empty() << endl; // 输出:0
	cout << q.size() << endl; //输出:4

	return 0;
}

队列与栈是一样的,使用 STL 容器适配出来的,是一种有特定操作数据方式的数据结构。没有迭代器,不支持遍历。如果你想查看队列 或者 栈里面的所有元素,你必须将数据一个一个从队列 或者栈中删除。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姬如祎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值