标准模板库(STL)之 queue 用法【初级】
文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。
资料仅供学习交流使用。
作者:Aliven888
1、简述
英文为SDK的官网描述,中文为本人翻译,如果不合理之处,请参照英文原描述观看:
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. 【队列是一种容器适配器,专门被设计用于FIFO的场景(先入先出),元素从容器的一端插入,并且从另外一端取出。】
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".【队列作为容器是适配器被实现,它们是使用特定容器类的封装对象作为其基础容器的类,提供了一组特定的成员函数来访问其元素。元素容器的“尾部”插入队列,然后从其“前部”取出。】
2、接口函数
名称 | 描述 |
---|---|
(constructor) | Construct queue (public member function ) |
empty | Test whether container is empty (public member function ) |
size | Return size (public member function ) |
front | Access next element (public member function ) |
back | Access last element (public member function ) |
push | Insert element (public member function ) |
emplace | Construct and insert element (public member function ) |
pop | Remove next element (public member function ) |
swap | Swap contents (public member function ) |
3、接口函数使用演示
定义一个变量:
std::queue<int> m_queueValue;
判断队列是否为空:
功 能:判断队列是否为空,为空返回true, 否则返回false
if (!m_queueValue.empty())
{
qDebug("m_queueValue is not empty.");
}
插入元素:
功 能:元素入队,从地=低地址到高地址依次是 [1, 2, 3, 4]
m_queueValue.push(1);
m_queueValue.push(2);
m_queueValue.push(3);
m_queueValue.push(4);
获取队列元素个数:
功 能:获取当前队列的元素个数。
int iSize = m_queueValue.size();
qDebug("m_queueValue iSize is [%d]", iSize);
队首元素出队:
功 能:元素出队,从队首(低地址)位置处出队,此时出队的元素是 1
int iElemet = m_queueValue.front();
qDebug("iElemet is [%d]", iElemet);
移除队首元素:
功 能:移除此时位于队首(低地址)位置处的元素,此时该元素是 1
m_queueValue.pop();
队尾元素出队:
功 能:获取队位于队尾(高地址)位置的元素 此时该元素是 4
iElemet = m_queueValue.back();
qDebug("iElemet is [%d]", iElemet);
队列插入元素:
C++ 11 引入的新特性
功 能:该函数的功能和 push() 函数类似,都是向队列中添加元素;此时队列的元素依次是 [2, 3, 4, 5]
m_queueValue.emplace(5);
队列元素互换:
C++ 11 引入的新特性
功 能:交换两个元素类型相同的队列中的元素,size随交换后的参数个数而变化;此时队列的元素依次是 m_queueValue = [6, 7, 8] queueChild = [2, 3, 4, 5]
std::queue<int> queueChild;
queueChild.push(6);
queueChild.push(7);
queueChild.push(8);
m_queueValue.swap(queueChild);
4、注意事项
1、队列中的元素是可以重复的。
2、队列的特点是先入队的元素先出队(FIFO)。