第十一天之queue容器

queue简介

queue是队列容器,是一种先进先出的容器
queue是简单的装饰了deque容器而成为的另一种容器
头文件需包含#include

queue对象的默认构造

queue 采用模板类实现,queue 对象的默认构造形式:queue queT; 如:
queue queInt; //一个存放 int 的 queue 容器。
queue queFloat; //一个存放 float 的 queue 容器。
queue queString; //一个存放 string 的 queue 容器。

//尖括号内还可以设置指针类型或自定义类型

queue的 push和pop方法

queue.push(elem); //往队尾添加元素
queue.pop(); //从队头移除第一个元素
queue<int> queInt;
queInt.push(1);queInt.push(3);
queInt.push(5);queInt.push(7);
queInt.push(9);queInt.pop();
queInt.pop();
此时 queInt 存放的元素是 5,7,9

queue对象的拷贝构造与赋值

queue(const queue &que); //拷贝构造函数
queue& operator=(const queue &que);//重载等号操作符
queue<int> queIntA;
queIntA.push(1);
queIntA.push(3);
queIntA.push(5);
queIntA.push(7);
queIntA.push(9);
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);
queIntA.push(7);
queIntA.push(9);
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);
queIntA.push(7);
queIntA.push(9);
if (!queIntA.empty())
{
int iSize = queIntA.size(); //5
}

案例

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

void main61()
{
	queue<int> q;
	q.push(1);
	q.push(3);
	q.push(5);

	cout << "队列头元素" << q.front() << endl;
	cout << "队列的大小" << q.size() << endl;

	while (!q.empty())
	{
		cout << q.front() << " ";
		q.pop();
	}
}
class Teacher
{
public:
	int age;
	char name[32];

	void printfT()
	{
		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.printfT();
		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->printfT();
		q.pop();
	}
}
void main()
{
	//main61();
	//main62();
	main63();
	system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值