C++ 标准模板库STL 队列 queue 使用方法与应用介绍

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

FIFO 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:

 
template < class T, class Container = deque<T> > class queue;


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.

 

posted @   zqlucky  阅读(3797)  评论(0编辑  收藏  举报
编辑推荐:
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
阅读排行:
· 历时 8 年,我冲上开源榜前 8 了!
· 分享一个我遇到过的“量子力学”级别的BUG。
· 物流快递公司核心技术能力-海量大数据处理技术
· 四大AI编程工具组合测评
· 关于能否用DeepSeek做危险的事情,DeepSeek本身给出了答案
点击右上角即可分享
微信分享提示