1. queue基本概念
概念:queue是一种先进先出的数据结构,它有两个出口。
队列容器允许从一端新增元素,从另一端移除元素。
队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为。
队列中进数据称为——入队。
队列中出数据称为——出队。
2. queue常用接口
功能描述:栈容器常用的对外接口。
构造函数:
queue<T> que;
//queue采用模板类实现,queue对象的默认构造形式queue(const queue &que);
//拷贝构造函数
赋值操作:
queue& operator=(const queue &que);
//重载等号操作符
数据存取:
push(elem);
//往队尾添加元素pop();
//从队头移除第一个元素back();
//返回最后一个元素front();
//返回第一个元素
大小操作:
empty();
//判断栈是否为空size();
//返回栈的大小
示例:
#include<iostream>
#include<queue>
using namespace std;
//队列queue容器
class Person{
public:
string name;
int age;
Person(string n,int a){
name=n;
age=a;
}
};
void test1(){
//创建队列
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);
cout<<"队列的大小:"<<q.size()<<endl;
//判断只要队列不为空,查看队头和对位,并出队
while(!q.empty()){
//查看队头
cout<<"队头元素为——姓名:"<<q.front().name<<" 年龄:"<<q.front().age<<endl;
//查看队尾
cout<<"队尾元素为——姓名:"<<q.back().name<<" 年龄:"<<q.back().age<<endl;
//出队
q.pop();
}
cout<<"队列的大小:"<<q.size()<<endl;
}
int main(){
test1();
system("pause");
return 0;
}
小结:
- 入队——push
- 出队——pop
- 返回队头元素——front
- 返回队尾元素——back
- 判断队是否为空——empty
- 返回队列大小——size
参考资料:https://www.bilibili.com/video/BV1et411b73Z?p=213