队列的基本概念
队列的定义
队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表,即遵循“先进先出/FIFO”的数据结构。
注意:只有队头和队尾能被外界访问,因此不允许有遍历行为。
队头(front):允许删除的一端,又称队首
队尾(rear):允许插入的一端
空队列:不包含任何元素的空表
队列的常用接口
构造函数
queue<T> que
//queue采用模板类实现,queue对象的默认构造形式queue(const queue &que)
//拷贝构造函数
赋值操作
-queue& operator==(const queue&que)
//重载等号操作符
数据存取
push(element)
//往队尾添加元素pop()
//从队头移除第一个元素back()
//返回最后一个元素front()
//返回第一个元素
大小操作
empty()
//判断队列是否为空.size()
//返回队列大小
举例
#include<iostream>
#include<queue>
#include<string>
using namespace std;
class Person
{
public:
Person(string name,int age);
{
this->m_Name=name;
this->m_Age=age;
}
string m_Name;
int m_Age;
}
void test01()
{
//创建队列
queue<Person>q;
//准备数据
Person p1("唐僧",30);
Person p2("孙悟空",1000);
Person p3("猪八戒",900);
Person p4("沙僧",800);
//入队
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
//判断只要队列不为空,查看队头和队尾,出队
while(!q.empty())
{
//查看队头
cout<<"队头元素---姓名:"<<q.front().m_Name<<"年龄:"<<q.front().m_Age<<endl;
//查看队尾
cout<<"队尾元素---姓名:"<<q.back().m_Name<<"年龄:"<<q.back().m_Age<<endl;
//出队
q.pop();
}
cout<<"队列大小为:"<<q.size()<<endl;
}
int main()
{
test01();
return 0;
}