C++数据结构---队列

队列是一种遵循先进先出(FIFO)原则的数据结构。在C++中,可以使用`queue`模板类来创建队列。队列可以通过`push`在后端添加元素,`pop`从前端删除元素,`empty`检查是否为空,`front`获取前端元素,`back`获取后端元素,以及`size`获取元素数量。文中通过示例代码展示了这些基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是队列

队列原理

如果我们单说队列,大家可能没有详细的概念

我们可以联想一下生活中的排队买东西

后来的人要排在先来的人的后面

同样的道理,先来的人肯定会比后来的人先结束购物

也就会先出队

这就是队列的原理—先进先出

队列格式

在C++中,我们可以用这种方式定义一个队列:

queue<数据类型,容器类型>队列名;

数据类型即bool,int,char

容器类型如果不填则默认为 deque 类型

deque 即普通队列类型,先进先出

例如:

queue<int>q;

队列常用函数

函数格式用法
push(元素)在队列末尾加入一个元素
pop()删除队列首位元素
empty()如果队列为空则返回true,否则为false
front()返回队列第一个元素
back()返回队列最后一个元素
size()返回队列的总元素个数
push_back(元素)强行插队,将元素插入队首

注:函数使用格式:队列名.函数

例:

q.empty();

示例:

  • push()
#include <bits/stdc++.h>
using namespace std;

queue<int>q;

int main()
{
	q.push(1);
	q.push(2);
	q.push(3);
	//此时正序输出队列:1,2,3
	return 0;
}

  • pop()
#include <bits/stdc++.h>
using namespace std;

queue<int>q;

int main()
{
	q.push(1);
	q.push(2);
	q.push(3);
	q.pop();
	//此时正序输出队列:2,3(1被删了) 
	return 0;
}

  • empty()
#include <bits/stdc++.h>
using namespace std;

queue<int>q;

int main()
{
	q.push(1);
	q.pop();
	cout<<q.empty(); //此时输出为true,队列内没有元素 
	return 0;
}

  • front()
#include <bits/stdc++.h>
using namespace std;

queue<int>q;

int main()
{
	q.push(1);
	q.push(2);
	cout<<q.front();//此时输出队列首位元素--1 
	return 0;
}

  • back()
#include <bits/stdc++.h>
using namespace std;

queue<int>q;

int main()
{
	q.push(1);
	q.push(2);
	cout<<q.back();//此时输出队列末尾元素--2
	return 0;
}
  • size()
#include <bits/stdc++.h>
using namespace std;

queue<int>q;

int main()
{
	q.push(1);
	q.push(2);
	q.pop();
	q.push(3);
	cout<<q.size();//此时队列内元素数量:2 
	return 0;
}

完结撒花~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

TE_OIer_lqy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值