从零开始学C++之STL(十一):容器适配器(stack、 queue 、priority_queue)源码浅析与使用示例

本文介绍了C++ STL中的三种容器适配器:stack、queue和priority_queue。stack基于deque、vector或list,实现先进后出(FIFO)原则;queue同样基于deque或list,遵循先进先出(FIFO);priority_queue使用vector或deque,实现优先级排序。文章通过源码解析和示例代码展示了它们的工作原理和使用方法,特别指出priority_queue不能用list实现,因为list不支持随机迭代器。
摘要由CSDN通过智能技术生成

一、容器适配器
stack
queue
priority_queue


stack、queue、priority_queue 都不支持任一种迭代器,它们都是容器适配器类型,stack是vector/deque/list对象创建了一个先进后出容器;queue是用deque或list对象创建了一个先进先出容器;priority_queue是用vector/deque创建了一个排序队列,内部用二叉堆实现。


前面或多或少谈到过list/vector的实现,而没提到过deque的实现,可以用以下一句话概括,具体可以看看《stl源码剖析》:

Storing contents in multiple smaller arrays, allocating additional arrays at the beginning or end as needed.
Indexing is implemented by keeping a dynamic array containing pointers to each of the smaller arrays.




(一)、stack

首先来看示例代码:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
#include <list>
#include <stack>

using  namespace std;

int main( void)
{
    stack< int, list< int> > s;
     for ( int i =  0; i <  5; i++)
    {
        s.push(i);
    }

     //for (size_t i=0; i<s.size(); i++)
     //{
     //  cout<<s.top()<<' ';   Error:size()一直在变化
     //  s.pop();
     //}

     while (!s.empty())
    {
        cout << s.top() <<  ' ';
        s.pop();
    }
    cout << endl;
     return  0;
}

再看stack 的源码:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// TEMPLATE CLASS stack
template <  class _Ty,
          class _Container = deque<_Ty> >
class stack
{
     // LIFO queue implemented with a container
public:
     typedef _Container container_type;
     typedef  typename _Container::va
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值