Queue容器的简介
queue是队列容器,是一个“先进先出”的容器。
queue是简单的装饰deque容器而成为另外的一种容器。
需要添加头文件:#include <queue>
queue 与stack 模板类很相似,queue 模板类也需要两个模板参数,一个是元素类型,一个容器类
型,元素类型是必要的,容器类型是可选的,默认为deque 类型。
queue队列也是一个线性存储表,与后进先出的堆栈不同,元素数据在表的一端插入,在另一端进行删除,即构成了先进先出FIFO表。插入的一端成为队尾,删除的一端成为队首。
C++ STL对queue队列的泛化,是通过模板类型,将默认的deque双端队列类型导入,在内部创建一个序列容器对象,来处理 queue队列的数据存储和操作,包括queue队列是否为空、取队首元素、取队尾元素、元素入队和元素出队等。由于仅需要取队首和队尾元素的操作,因此queue队列容器并不提供任何类型的迭代器。
queue的默认构造:
template <class T>
queue<T> zploo; //queue采用模板类实现,queue对象的默认构造形式。
queue<int> zploo; //一个存放int的queue容器。
queue<float> zploo; //一个存放float的queue容器。
queue<string> zploo; //一个存放string的queue容器。
/*尖括号内还可以设置指针类型 或 自定义类型*/
queue的拷贝构造和赋值:
queue(const queue& zploo); //拷贝构造函数
queue& operator= (const queue &zploo); //重载等号操作符
queue的push() 和 pop() 方法:
queue.push(elem); //往队尾添加元素
queue.pop(); //从对头移除第一个元素
queue的数字存取:
queue.back(); //返回最后一个元素
queue.front(); //饭后第一个元素
queue的大小:
queue.empty(); //判断队列是否为空
queue.size(); //返回队列的大小
练习演示代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <queue>
#include <string>
using namespace std;
class Student
{
public:
Student(string name, int id) {
this->name = name;
this->id = id;
}
void show()
{
cout << name << ", " << id << endl;
}
private:
string name;
int id;
};
void testQueue1()
{
queue<int> q;
q.push(1); //队头
q.push(2);
q.push(3);
q.push(4);
q.push(5); //队尾
int value = q.front();
q.pop();
cout << value << "出队了" << endl;
q.front() = 100;
q.back() = 200;
//遍历
while (!q.empty()) {
cout << q.front() << "出队了" << endl;
q.pop();
}
Student s1("张2", 1);
Student s2("张3", 2);
Student s3("张4", 3);
Student s4("张5", 4);
queue<Student> qS;
qS.push(s1);
qS.push(s2);
qS.push(s3);
qS.push(s4); //入队
while (!qS.empty()) {
qS.front().show();
qS.pop();
}
cout << " ----" << endl;
queue<Student *> qSR;
qSR.push(&s1);
qSR.push(&s2);
qSR.push(&s3);
qSR.push(&s4);
while (!qSR.empty()) {
qSR.front()->show();
qSR.pop();
}
}
int main(void)
{
testQueue1();
return 0;
}