C++ 标准模板库STL 队列 queue 使用方法与应用介绍
queue
queue模板类的定义在<queue>头文件中。
与stack模板类很相似,queue模板类也需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque类型。
定义queue对象的示例代码如下:
queue<int> q1;
queue<double> q2;
queue的基本操作有:
入队,如例:q.push(x); 将x接到队列的末端。
出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
访问队首元素,如例:q.front(),即最早被压入队列的元素。
访问队尾元素,如例:q.back(),即最后被压入队列的元素。
判断队列空,如例:q.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:q.size()
std::queue
queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other.
queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front".
The underlying container may be one of the standard container class template or some other specifically designed container class. The only requirement is that it supports the following operations:
- front()
- back()
- push_back()
- pop_front()
Therefore, the standard container class templates deque and list can be used. By default, if no container class is specified for a particular queue class, the standard container class template deque is used.
In their implementation in the C++ Standard Template Library, queues take two template parameters:
|
|
Where the template parameters have the following meanings:
- T: Type of the elements.
- Container: Type of the underlying container object used to store and access the elements.
In the reference for the queue member functions, these same names are assumed for the template parameters.