閱讀359 返回首頁    go 阿裏雲 go 技術社區[雲棲]


STL stack應用

1. 概念 
stack是一種LIFO(last-in first-out)的數據結構,其隻允許在容器的尾部對數據進行操作,如下: 

FEAL2_V8MKB8DJ56D7ZWHMW
stack
定義如下: 
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from the end of the container. 
stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.

2. API 
stack提供的API接口比較簡單,如下: 
(constructor)    Construct stack (public member function) 
empty    Test whether container is empty (public member function) 
size    Return size (public member function) 
top    Access next element (public member function) 
push    Add element (public member function) 
pop    Remove element (public member function)

3. stack實現 
stack是容器適配器,其通過對某種既有容器進行包裝,從而提供LIFO的數據訪問方法。不同的庫,對stack有不同的實現,可以為deque,或者list,也可以為其他實現。 
例如,SGI SQL就是通過deque實現stack,主要代碼如下: 

[c-sharp] view plaincopy
  1. template <class T, class Sequence = deque<T> >  
  2. class stack {  
  3. Sequence c; // 底層容器  
  4. public:  
  5. // 通過調用deque的方法完成 stack 的操作。  
  6. bool empty() const { return c.empty(); }  
  7. size_type size() const { return c.size(); }  
  8. reference top() { return c.back(); }  
  9. const_reference top() const { return c.back(); }  
  10. void push(const value_type& x) { c.push_back(x); }  
  11. void pop() { c.pop_back(); }  
  12. };  

4. 迭代器 
stack所有元素的進出都必須符合LIFO的條件,隻有stack頂端的元素,才能被訪問,所以,stack不提供迭代器。


5. stack使用示例 
代碼如下: 

[c-sharp] view plaincopy
  1. #include <iostream>  
  2. #include <stack>  
  3. using namespace std;  
  4.   
  5. int main ()  
  6. {  
  7.   stack<int> myints;  
  8.   cout << "0. size: " << (int) myints.size() << endl;  
  9.   
  10.   for (int i=0; i<5; i++) myints.push(i);  
  11.   cout << "1. size: " << (int) myints.size() << endl;  
  12.   
  13.   myints.pop();  
  14.   cout << "2. size: " << (int) myints.size() << endl;  
  15.   
  16.   return 0;  
  17. }  
輸出結果: 0. size: 0 1. size: 5 2. size: 4

6. 結語 
Stack是一個容器適配器,通過包裝既有容器,從而為程序員提供了堆棧的全部功能。 

參考文獻: 
STL源碼剖析 

最後更新:2017-04-04 07:03:55

  上一篇:go Google公布2012年度最佳Android應用排行榜
  下一篇:go 微軟要當心了:多部遊戲移植至OS X