3.6 queue 容器
3.6.1 queue 基本概念
概念:Queue是一种先进先出(First In First Out,FIFO)的数据结构,他有两个出口
队列容器允许从一端新增元素,从另一端移除元素
队列中只有对头和对位才可以被外界使用,因此队列不允许有遍历行为
队列中进数据称为 — 入队(push)
队列中出数据称为 — 出队(pop)
3.6.2 queue 常用接口
功能描述:
- 队列容器常用的对外接口
构造函数:
queue<T> q;
//queue 采用模板类实现,queue 对象的默认构造形式queue(const queue& q);
//拷贝构造函数
赋值操作:
queue& operator=(const queue& q);
//重载等号操作符
数据存取:
push(elem);
//向队尾添加元素pop();
//从队头移除一个元素back();
//返回最后一个元素front();
//返回第一个元素
大小操作:
empty();
//判断队列是否为空size();
//返回队列的大小
示例:
#include<iostream>
#include<queue>
#include<string>
using namespace std;
//queue常用接口
class Person {
public:
string m_name;
int m_age;
Person(string name, int age) {
this->m_name = name;
this->m_age = age;
}
};
//为了方便输出,重载“<<”
ostream& operator<<(ostream& out, Person& p) {
out << "name:" << p.m_name << " age:" << p.m_age;
return out;
}
void test01() {
queue<Person> q;
//准备数据
Person p1("张三",10);
Person p2("李四",20);
Person p3("王五",30);
Person p4("赵六",40);
//入队
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
//判断,只要队头不为空,查看队头,查看队尾,出队
while (!q.empty()) {
cout << "队头:" << q.front() << endl;
cout << "队尾:" << q.back() << endl;
cout << "队列大小为:" << q.size() << endl;
cout << "————————————————————————————" << endl;
q.pop();
}
}
//主函数
int main() {
test01();
system("pause");
return 0;
}