STL源码剖析笔记:Deque、Stack、Queue

一、Deque 双端队列

特点:双向进出的分段连续线性空间。

 1 typedef T value_type;
 2 typedef value_type* pointer;
 3 typedef size_t size_type;
 4 
 5 typedef __deque_iterator<T,T&,T*,BufSize> iterator;
 6 
 7 typedef pointer* map_pointer;
 8 
 9 iterator start;                  //第一个节点
10 iterator finish;                //最后一个节点
11 map_pointer map;         //其中每个元素都是指针
12 size_type map_size;      //map内有多少指针
13 
14 iterator begin() {return start;}
15 iterator end() {return finish;}
16 
17 reference front() {return *start;}
18 reference back() {
19     iterator tmp = finish;
20     --tmp;
21     return *tmp;
22 }
23 size_type size() const{return finish-start;}
24 size_type max_size() const{return size_type(-1);}
25 bool empty() const{return finish==start;}
 1 void push_back(const value_type& t){
 2     if(finish.cur != finish.last -1){   //最后缓冲区尚有一个以上空间
 3         construct(finish.cur,t);   //在备用空间构造元素1
 4         ++finish.cur;  
 5     }
 6     else
 7         push_back_aux(t);
 8 }
 9 void push_front(const value_type& t){
10     if(start.cur != start.first){   //第一缓冲区尚有备用空间
11         construct(start.cur -1, t);   //在备用空间构造元素
12         --start.cur;  
13     }
14     else
15         push_front_aux(t);
16 }
17 void pop_back(){
18     if(finish.cur != finish.first){   //最后缓冲区尚有元素
19     --finish.cur;   
20     destory(finish.cur);
21     }
22     else
23         //最后缓冲区没有元素
24         pop_back_aux();
25 }
26 void pop_front(){
27     if(start.cur != start.last-1){  //第一缓冲区尚有元素
28         destory(start.cur);   //将第一元素结构
29         ++start.cur;
30     }
31     else
32         //第一缓冲区有一个元素
33         pop_front_aux();   //缓冲区释放
34 }
插入 删除 访问

push_front

O(1)

pop_front

O(1)

O(1)

push_back

O(1)

pop_back

O(1)

insert

O(n)

erase

O(n)

 

二、Stack

特点:先进后出,不允许遍历,所以没有迭代器。

1 Sequence c;    //底层容器
2 bool empty() const{return c.empty(); }
3 size_type size() const{return c.size();}
4 reference top() {return c.back();}
5 const_reference top() const{return c.back();}
6 void push(const value_type& x){c.push_back(x);}
7 void pop(){c.pop_back();}

 三、Queue

特点:先进先出,不允许遍历,所以没有迭代器。

1 Sequence c;    //底层容器
2 bool empty() const{return c.empty();}
3 size_type size() const{return c.size();}
4 reference front() {return c.front();}
5 const_reference front() const {return c.front();}
6 reference back(){return c.back();}
7 const_reference back() const{return c.back();}
8 void push(const value_type& x){c.push_back(x);}
9 void pop(){c.pop_front();}
posted @ 2022-07-21 15:51  番茄玛丽  阅读(33)  评论(0编辑  收藏  举报