栈(statck)这种数据结构在计算机中是相当出名
的。栈中的数据是先进后出的(First In Last Out,
FILO)。栈只有一个出口,允许新增元素(只能在栈顶上增加)、移出元素(只能移出栈顶元素)、取得栈顶元素等操作。在STL中,栈是以别的容器作为底
部结构,再将接口改变,使之符合栈的特性就可以了。因此实现非常的方便。下面就给出栈的函数列表和VS2008中栈的源代码,在STL中栈一共就5个常用
操作函数(top()、push()、pop()、 size()、empty() ),很好记的。 
VS2008中栈的源代码 友情提示:初次阅读时请注意其实现思想,不要在细节上浪费过多的时间。 -
- template<class _Ty, class _Container = deque<_Ty> >
- class stack
- {
- 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()
- {
- }
-
- explicit stack(const _Container& _Cont) : c(_Cont)
- {
- }
-
- 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());
- }
-
- void push(const value_type& _Val)
- {
- c.push_back(_Val);
- }
-
- void pop()
- {
- c.pop_back();
- }
-
- const _Container& _Get_container() const
- {
- return (c);
- }
-
- protected:
- _Container c;
- };
可以看出,由于栈只是进一步封装别的数据结构,并提供自己的接口,所以代码非常简洁,如果不指定容器,默认是用deque来作为其底层数据结构的(对deque不是很了解?可以参阅《STL系列之一 deque双向队列》)。下面给出栈的使用范例: -
-
- #include <stack>
- #include <vector>
- #include <list>
- #include <cstdio>
- using namespace std;
- int main()
- {
-
- 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;
- }
|