天天看點

STL stack應用

1. 概念 

stack是一種lifo(last-in first-out)的資料結構,其隻允許在容器的尾部對資料進行操作,如下: 

STL stack應用

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

template <class t, class sequence = deque<t> >  

class stack {  

sequence c; // 底層容器  

public:  

// 通過調用deque的方法完成 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(); }  

void push(const value_type& x) { c.push_back(x); }  

void pop() { c.pop_back(); }  

};  

4. 疊代器 

stack所有元素的進出都必須符合lifo的條件,隻有stack頂端的元素,才能被通路,是以,stack不提供疊代器。

5. stack使用示例 

代碼如下: 

[c-sharp] view plaincopy

#include <iostream>  

#include <stack>  

using namespace std;  

int main ()  

{  

  stack<int> myints;  

  cout << "0. size: " << (int) myints.size() << endl;  

  for (int i=0; i<5; i++) myints.push(i);  

  cout << "1. size: " << (int) myints.size() << endl;  

  myints.pop();  

  cout << "2. size: " << (int) myints.size() << endl;  

  return 0;  

}  

輸出結果:

0. size: 0

1. size: 5

2. size: 4

6. 結語 

stack是一個容器擴充卡,通過包裝既有容器,進而為程式員提供了堆棧的全部功能。 

參考文獻: 

stl源碼剖析 

繼續閱讀