[TOC]

定义

queue是一种容器转换器模板,调用#include< queue>即可使用队列类。

一、queue初始化

queue<Type, Container> (<数据类型,容器类型>)
初始化时必须要有数据类型,容器可省略,省略时则默认为deque 类型

1
2
3
4
5
queue<int>q1;

queue<double>q2;

queue<char>q3;
1
2
3
4
5
queue<char, list<char>>q1;
//用list容器实现的queue

queue<int, deque<int>>q2;
//用deque容器实现的queue

二、queue常用函数

1.常用函数

  1. push() 在队尾插入一个元素
  2. pop() 删除队列第一个元素
  3. size() 返回队列中元素个数
  4. empty() 如果队列空则返回true
  5. front() 返回队列中的第一个元素
  6. back() 返回队列中最后一个元素

2.函数运用示例

(1)push()在队尾插入一个元素

1
2
3
4
queue <string> q;
q.push("first");
q.push("second");
cout<<q.front()<<endl;

输出 first

(2)pop() 将队列中最靠前位置的元素删除,没有返回值

1
2
3
4
5
queue <string> q;
q.push("first");
q.push("second");
q.pop();
cout<<q.front()<<endl;

输出 second

(3)size() 返回队列中元素个数

1
2
3
4
queue <string> q;
q.push("first");
q.push("second");
cout<<q.size()<<endl;

输出2

(4)empty() 如果队列空则返回true

1
2
3
4
5
queue <string> q;
cout<<q.empty()<<endl;
q.push("first");
q.push("second");
cout<<q.empty()<<endl;

分别输出1和0

(5)front() 返回队列中的第一个元素

1
2
3
4
5
6
queue <string> q;
q.push("first");
q.push("second");
cout<<q.front()<<endl;
q.pop();
cout<<q.front()<<endl;

第一行输出first;
第二行输出second

(6)back() 返回队列中最后一个元素

1
2
3
4
queue <string> q;
q.push("first");
q.push("second");
cout<<q.back()<<endl;

输出最后一个元素second