原文地址:
http://blog.csdn.net/morewindows/article/details/6950881
棧(statck)這種數據結構在計算機中是相當出名的。棧中的數據是先進後出的(First In Last Out, FILO)。棧只有一個出口,允許新增元素(只能在棧頂上增加)、移出元素(只能移出棧頂元素)、取得棧頂元素等操作。在STL中,棧是以別的容器作爲底部結構,再將接口改變,使之符合棧的特性就可以了。因此實現非常的方便。下面就給出棧的函數列表和VS2008中棧的源代碼,在STL中棧一共就5個常用操作函數(top()、push()、pop()、 size()、empty() ),很好記的。
VS2008中棧的源代碼
友情提示:初次閱讀時請注意其實現思想,不要在細節上浪費過多的時間。
- //VS2008中 stack的定義 MoreWindows整理(http://blog.csdn.net/MoreWindows)
- template<class _Ty, class _Container = deque<_Ty> >
- class stack
- { // LIFO queue implemented with a container
- public:
- typedef _Container container_type;
- typedef typename _Container::value_type value_type;
- typedef typename _Container::size_type size_type;
- typedef typename _Container::reference reference;
- typedef typename _Container::const_reference const_reference;
- stack() : c()
- { // construct with empty container
- }
- explicit stack(const _Container& _Cont) : c(_Cont)
- { // construct by copying specified container
- }
- bool empty() const
- { // test if stack is empty
- return (c.empty());
- }
- size_type size() const
- { // test length of stack
- return (c.size());
- }
- reference top()
- { // return last element of mutable stack
- return (c.back());
- }
- const_reference top() const
- { // return last element of nonmutable stack
- return (c.back());
- }
- void push(const value_type& _Val)
- { // insert element at end
- c.push_back(_Val);
- }
- void pop()
- { // erase last element
- c.pop_back();
- }
- const _Container& _Get_container() const
- { // get reference to container
- return (c);
- }
- protected:
- _Container c; // the underlying container
- };
可以看出,由於棧只是進一步封裝別的數據結構,並提供自己的接口,所以代碼非常簡潔,如果不指定容器,默認是用deque來作爲其底層數據結構的(對deque不是很瞭解?可以參閱《STL系列之一 deque雙向隊列》)。下面給出棧的使用範例:
- //棧 stack支持 empty() size() top() push() pop()
- // by MoreWindows(http://blog.csdn.net/MoreWindows)
- #include <stack>
- #include <vector>
- #include <list>
- #include <cstdio>
- using namespace std;
- int main()
- {
- //可以使用list或vector作爲棧的容器,默認是使用deque的。
- stack<int, list<int>> a;
- stack<int, vector<int>> b;
- int i;
- //壓入數據
- for (i = 0; i < 10; i++)
- {
- a.push(i);
- b.push(i);
- }
- //棧的大小
- printf("%d %d\n", a.size(), b.size());
- //取棧項數據並將數據彈出棧
- while (!a.empty())
- {
- printf("%d ", a.top());
- a.pop();
- }
- putchar('\n');
- while (!b.empty())
- {
- printf("%d ", b.top());
- b.pop();
- }
- putchar('\n');
- return 0;
- }
轉載請標明出處,原文地址:http://blog.csdn.net/morewindows/article/details/6950881