【STL】queue容器

Queue简介#

  • queue是队列容器,是一种“先进先出”的容器。
  • queue是简单地装饰deque容器而成为另外的一种容器。
  • #include<queue>

queue对象的默认构造#

queue采用模板类实现

queue<T> queT;               //queue对象的默认构造形式:
queue<int> queInt;            //一个存放int的queue容器。
queue<float> queFloat;     //一个存放float的queue容器。
queue<string> queString;     //一个存放string的queue容器。
...				    
//尖括号内还可以设置指针类型或自定义类型。

queue的push()与pop()方法#

  • queue.push(elem); //往队尾添加元素
  • queue.pop(); //从队头移除第一个元素
queue<int> queInt;
queInt.push(1);
queInt.push(3);
queInt.pop();

queue对象的拷贝构造与赋值#

  • queue(const queue &que); //拷贝构造函数
  • queue& operator=(const queue &que); //重载等号操作符
queue<int> queIntA;
queIntA.push(1);
queIntA.push(3);
queIntA.push(5);
		
queue<int> queIntB(queIntA);	//拷贝构造
queue<int> queIntC;
queIntC = queIntA;				//赋值

queue的数据存取#

  • queue.back(); //返回最后一个元素
  • queue.front(); //返回第一个元素
queue<int> queIntA;
queIntA.push(1);
queIntA.push(3);
queIntA.push(5);

int iFront = queIntA.front();	//1
int iBack = queIntA.back();		//9

queIntA.front() = 11;			//11
queIntA.back() = 19;			//19

queue的大小#

  • queue.empty(); //判断队列是否为空
  • queue.size(); //返回队列的大小
queue<int> queIntA; 	
queIntA.push(1);   	
queIntA.push(3);  		
queIntA.push(5);		

if (!queIntA.empty())
{
	int iSize = queIntA.size();		//3
}

应用案例#

//队列模型
#include <iostream>
#include <queue>
using namespace std;

//队列中基本数据类型
void main61()
{
	queue<int>  q;
	q.push(1);
	q.push(2);
	q.push(3);

	cout << "队头元素:" << q.front() << endl;
	cout << "队列的大小" << q.size() <<endl;
	while ( !q.empty())
	{
		int tmp = q.front();
		cout << tmp << " ";
		q.pop();
	}
}

//队列的算法 和 数据类型的分离

//teacher结点
class Teacher
{
public:
	int		age;
	char	name[32];
public:
	void printT()
	{
		cout << "age:" << age << endl;
	}
};

void main62()
{
	Teacher t1, t2, t3;
	t1.age = 31;
	t2.age = 32;
	t3.age = 33;
	queue<Teacher> q;
	q.push(t1);
	q.push(t2);
	q.push(t3);

	while (!q.empty())
	{
		Teacher tmp = q.front();
		tmp.printT();
		q.pop();
	}
}
void main63()
{
	Teacher t1, t2, t3;
	t1.age = 31;
	t2.age = 32;
	t3.age = 33;
	queue<Teacher *> q;
	q.push(&t1);
	q.push(&t2);
	q.push(&t3);

	while (!q.empty())
	{
		Teacher *tmp = q.front();
		tmp->printT();
		q.pop();
	}
}

int main()
{
	//main61();
	//main62();
	main63();
	return 0;
}

作者:tazimi

出处:https://www.cnblogs.com/tazimi/p/13322845.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   tazimi  阅读(126)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示