18.6.2 queue常用接口
queue容器成员函数比较简单,放在一起介绍。
构造函数:
queue<T> que;
//默认构造函数queue(const queue &que);
//拷贝构造函数
赋值操作:
queue& operator=(const queue &que);
//等号运算符重载
数据存取:
push(ele);
//往队尾添加元素pop();
//删除队头第一个元素back();
//返回最后一个元素front();
//返回第一个元素
大小操作:
empty();
//判断容器是否为空size();
//返回容器元素个数
示例也是非常的简单
这里是用自定义数据类型来作为示例。
#include <iostream>
#include <queue>
#include <sstream>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
this->name = name;
this->age = age;
}
string name;
int age;
string printInfo()
{
stringstream personInfo;
personInfo << "姓名:" << this->name << "\t年龄:" << this->age;
return personInfo.str();
}
};
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().printInfo() << endl;
cout << "队尾元素:" << q.back().printInfo() << endl;
q.pop();
}
cout << "队列大小为:" << q.size() << endl;
}
int main()
{
test1();
}