Queue队列的基本内容
Class queue<>实现出一个queue。你可以使用push()将任意数量的元素放入queue中,也可以使用pop()将元素依其插入次序从容器中移除。换句话说,queue是一个典型的数据缓冲构造。
为了运用 queue你必须先包含头文件<queue>:
#include<queue>
在头文件<queue>中,class queue定义如下:
namespace std {
template <typename T,typename Container = deque<T>>
class queue;
}
第一个template 参数代表元素类型。带有默认值的第二个template 参数定义queue 内部用来
存放元素的实际容器,默认采用deque。例如下面的例子定义出了一个内含string的 queue:
std::queue<std::string> buffer;
实际上queue 只是很单纯地把各项操作转化为内部容器的对应调用。你可以使用任何sequence容器支持queue,只要它们支持front(),back(),push_back()和pop_front ()等操作。例如你可以使用 list 来容纳元素:
std::queue<std::string,std::list<std::string>> buffer;
Queue的核心接口
Queue 的核心接口主要由成员函数push(),front(),back()和pop()构成:
push():将一个元素放入queue内。
pop():从queue中移除一个元素。
front ():返回 queue 内的下一个元素(也就是第一个被放入的元素)。
back():返回queue内的最后一个元素(也就是最后一个被放入的元素)
注意,pop()虽然移除下一个元素,但是并不返回它,front()和back()返回下一个元素,但并不移除它。注意,如果queue 内没有元素,则front(),back()和pop()的执行会导致不确定的行为。你可以采用成员函数size()和empty()来检验容器是否为空。
Queue运用实例
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main(){
queue<string> q;
q.push("These ");
q.push("are ");
q.push("more than ");
cout << q.front();
q.pop();
cout << q.front();
q.pop();
q.push("four ");
q.push("words!");
q.pop();
cout << q.front();
q.pop();
cout << q.front() << endl;
q.pop();
cout << "number of elements in the queue: " << q.size()
<< endl;
}
输出结果为:
These are four words!
number of elements in the queue: 0
细究Class queue<>
queue的接口或多或少直接映射了容器内部所用的相应成员。请参照上篇博客中细究Class stack<>中的内容,思路基本相似。