STL—queue

简介: queue翻译为队列,在STL中实现了一个先进先出的容器,意思是先插入到队列中的元素先出队,我们也可以通过数组去模拟一个队列,具体操作见博客:用数组模拟队列,本博客讲述STL中的queue的应用,要想使用queue,需要添加头文件:#include <queue>

文章目录

一、什么是queue

二、queue的操作

1.queue的定义

2.queue容器内元素的访问

3.queue中的函数

(1)push()

(2)front(),back()

(3)pop()

(4)empty()

(5)size()


一、什么是queue

queue翻译为队列,在STL中实现了一个先进先出的容器,意思是先插入到队列中的元素先出队,我们也可以通过数组去模拟一个队列,具体操作见博客:用数组模拟队列,本博客讲述STL中的queue的应用,要想使用queue,需要添加头文件:#include <queue>


二、queue的操作

1.queue的定义

queue<typename> name;

2.queue容器内元素的访问

由于队列queue是一种先进先出的限制性的数据结构,因此STL中只能通过front()来访问队首元素,或是通过back()来访问队尾元素,push()是入队操作

#include <iostream>
#include <queue>
using namespace std;
int main()
{
    queue<int> q;
    for (int i = 1; i <= 5; i ++ ) q.push(i);
    cout << q.front() << ' ' << q.back();
    return 0;
}

输出结果为:1 5

3.queue中的函数

(1)push()

q.push(x);把x入队,时间复杂度为O(1),实例见queue容器内元素的访问


(2)front(),back()

q.front();,q.back();可以分别获得队首元素和队尾元素,时间复杂度为O(1),实例见queue容器内元素的访问


(3)pop()

q.pop();是令队首元素出队,时间复杂度为O(1)

#include <iostream>
#include <queue>
using namespace std;
int main()
{
    queue<int> q;
    for (int i = 1; i <= 5; i ++ ) q.push(i);
    for (int i = 1; i <= 4; i ++ ) q.pop();
    cout << q.front();
    return 0;
}

输出结果为:5

(4)empty()

q.empty();用来检测queue是否为空,如果是空则返回true,否则返回false,时间复杂度为O(1)

#include <iostream>
#include <queue>
using namespace std;
int main()
{
    queue<int> q;
    if(q.empty()) cout << "EMPTY" << endl;
    else cout << "NOT EMPTY" << endl;
    for (int i = 1; i <= 5; i ++ ) q.push(i);
    if(q.empty()) cout << "EMPTY" << endl;
    else cout << "NOT EMPTY" << endl;
    return 0;
}

输出结果为:

EMPTY

NOT EMPYTY

(5)size()

q.size();用来返回queue内元素的个数,时间复杂度为O(1)

#include <iostream>
#include <queue>
using namespace std;
int main()
{
    queue<int> q;
    for (int i = 1; i <= 5; i ++ ) q.push(i);
    cout << q.size();
    return 0;
}

输出结果为:5



目录
相关文章
|
4月前
|
容器
STL_queue
STL_queue
19 1
|
6天前
Queue和deque用法
Queue和deque用法
7 0
|
1月前
|
C++ 容器
【C++初阶】STL详解(六)Stack与Queue的介绍与使用
【C++初阶】STL详解(六)Stack与Queue的介绍与使用
19 1
|
3月前
|
存储 C++ 容器
STL--stack、queue实现
STL--stack、queue实现
|
9月前
|
存储 设计模式 C++
C++ STL stack & queue
stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行元素的插入与提取操作。
|
9月前
|
存储 算法 C++
C++ STL priority_queue
优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
|
7月前
|
存储 算法 程序员
stack、queue、priority_queue的使用和简单实现【STL】
stack、queue、priority_queue的使用和简单实现【STL】
30 0
|
10月前
|
C++ 容器
【C++ STL】 --- queue
【C++ STL】 --- queue
38 0
|
11月前
|
设计模式 C++ 容器
C++【STL】之stack和queue学习
C++ STL stack和queue常用接口和模拟实现详细讲解,干货满满!
83 0
C++【STL】之stack和queue学习
|
11月前
|
存储 算法 C++
C++【STL】之priority_queue学习
C++ STL 优先级队列,常用接口的使用和模拟实现详细讲解,干货满满!
70 1
C++【STL】之priority_queue学习