- Stack是一種先進后出的數據結構,他只有一個出口
- stack允許 新增元素、移除元素、取得最頂端的元素,但是無法獲得stack的內部數據,因此satck沒有遍歷行為

?Stack定義的完整列表 (雙端隊列作為Stack的底層容器)
- 將deque作為Stack的底部結構,對其原有的接口進行適配,使其滿足"先進后出"的特性
- deque是雙向開口的數據結構,只需要封閉deque的頭端開口(缺省實現),便輕而易舉的形成了一個stack。
- Stack基于deque,這種“修改某物的接口 形成另外一種事物的”的性質歸結為 adapter (配接器),因此將stack不歸類為容器,而將其歸結為 container adapter (容器適配器)
- 先前自己寫的 STL版的 deque 缺失的代碼比較多,因此下面的代碼中?class Sequence = std::deque<T> 借用STL標準庫的deque實現
//定義在stl_config.h文件中
//但是沒有找到 具體詳情參見 參考鏈接
# ifdef __STL_EXPLICIT_FUNCTION_TMPL_ARGS
# define __STL_NULL_TMPL_ARGS <>
# else
# define __STL_NULL_TMPL_ARGS
# endiftemplate <class T,class Sequence = std::deque<T>>
class stack{//__STL_NULL_TMPL_ARGS會展開為 <> friend bool operator== __STL_NULL_TMPL_ARGS(const stack&,const stack&);friend bool operator< __STL_NULL_TMPL_ARGS(const stack&,const stack&);
public:typedef typename Sequence::value_type value_type;typedef typename Sequence::size_type size_type;typedef typename Sequence::reference reference;typedef typename Sequence::const_reference const_reference;
protected://底層容器Sequence c;
public://以下完全使用Sequence c的操作,完成stack的操作bool empty() const {return c.empty();}size_type size() const {return c.size();}reference top() {return c.back();}const_reference top() const {return c.back();}//deque 是兩頭可以進出,stack是末端進,末端出 (所以后進者先出)void push(const value_type& x){ c.push_back(x);}void pop(){return c.pop_back();}
};template <class T,class Sequence>
bool operator==(const stack<T,Sequence>&x,const stack<T,Sequence>&y){return x.c == y.c;
}template <class T,class Sequence>
bool operator<(const stack<T,Sequence>&x,const stack<T,Sequence>&y){return x.c < y.c;
}
Stack沒有迭代器
- 考慮到只有stack的頂端的元素才會被外界取用,因此 stack不需要提供遍歷元素的迭代器
基于底層容器鏈表list的Stack
- Stack需要的函數如 empty、size()、back、push_back、pop_back是鏈表也支持的
- 使用范例
#include <stack>
#include <list>
#include <iostream>
#include <algorithm>int main(){std::stack<int,std::list<int>>list_stack;list_stack.push(1);list_stack.push(3);list_stack.push(5);list_stack.push(7);std::cout << list_stack.size() << std::endl; //4std::cout << list_stack.top() << std::endl; //7list_stack.pop();std::cout << list_stack.top() << std::endl; //5list_stack.pop();std::cout << list_stack.top() << std::endl; //3list_stack.pop();std::cout << list_stack.top() << std::endl; //1std::cout << list_stack.size() << std::endl; //1
}
參考鏈接
- 【c++從菜雞到王者】第六篇:詳解晦澀難懂的c++語法_Sefr后端-CSDN博客
- SGI STL-----__STL_NULL_TMPL_ARGS_yde的博客-CSDN博客
- 《STL源碼剖析》-- stl_config.h_一個人的戰爭-CSDN博客