一、基本概念
1、queue是一种先进先出的数据结构,队尾只能进数据,队头只能出数据。
2、队列容器允许从一端新增数据,另一端移除数据。
3、只有队头和队尾可以被外界访问到。
4、进数据称为入队,出数据称为出队。
二、常用接口
1、queue容器常用接口:
queue<int>q;
q.push(1); // 向队列q中添加元素1(只能从队列尾部添加元素)
q.pop(); // 将队列头元素弹出(只能从队列头弹出元素)
q.front(); // 求该队列头部元素值
q.back(); // 求队尾元素的值
q.size(); //求该队列中元素的个数
q.empty(); //判断队列是否为空
q.swap(tq); // 交换两个队列中的内容
2、应用实例:
#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
class Person
{
public:
string m_Name;
int m_Age;
Person(string name, int age)
{
m_Name = name;
m_Age = age;
}
};
void Test01()
{
queue<Person> q;
Person p1("A", 10);
Person p2("B", 20);
Person p3("C", 30);
Person p4("D", 40);
// 入队
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();
cin.get();
}