stack的常見用法詳解
說在前面:
stack翻譯爲棧,是STL中實現的一個後進先出的容器。要使用 stack,應先添加頭文件include。
-
stack的定義
其定義的寫法和其他STL容器相同, typename可以任意基本數據類型或容器:
stack<typename> name;
-
stack容器內元素的訪問與常用函數實列解析
- 先出的數據結構,在STL的 stack中只能通過top()來訪問棧頂元素。
- push(x)將x入棧,時間複雜度爲O(1),實例見“ stack容器內元素的訪問。
- top()獲得棧頂元素,時間複雜度爲O(1),實例見“ stack容器內元素的訪問。
- pop()用以彈出棧頂元素,時間複雜度爲O(1)。
- empty()可以檢測stack是否爲空,返回true爲空,返回false爲非空,時間複雜度爲O(1)。
- size()返回stack內元素的個數,時間複雜度爲O(1)。
#include <iostream> #include <stack> using namespace std; int main() { stack<int> s; int t; for (int i=1;i<5;i++) { t=i; s.push(t); // 壓棧 } while(!s.empty()) // 判斷非空 { cout<<s.top(); // 打印頂部元素 s.pop(); // 移除棧頂元素 if(s.size()!=0) // 測棧中元素的多少; cout<<" "; } cout<<endl; return 0; } // 輸出: 4 3 2 1
-
stack常見用途
-
stack用來模擬實現一些遞歸,防止程序對棧內存的限制而導致程序運行出錯。一般來說,程序的棧內存空間很小,對有些題目來說,如果用普通的函數來進行遞歸,一旦遞歸層數過深(不同機器不同,約幾千至幾萬層),則會導致程序運行崩潰。如果用棧來模擬遞歸算法的實現,則可以避免這一方面的問題(不過這種應用出現較少)。
下面我舉幾個實例來展示stack的用法示例
-
10進制轉二進制
可以通過棧這個數據結構實現
#include <iostream> #include <stack> using namespace std; stack<int> s; // 儲存每一次對2取餘的結果 void turn (int t) { while(t!=0) { s.push(t%2); t/=2; } } int main() { int t; while(cin>>t) { turn (t); while(!s.empty()) { cout<<s.top(); s.pop(); } cout<<endl; } return 0; }
-
將字符串逆序輸出
例如將 str="nice to meet you @ qiuqiu"逆序輸出。
ps:關於sstream輸入輸出流建議大家看一下這篇文章
傳送門
#include <iostream> #include <stack> #include <sstream> using namespace std; int main() { string str("nice to meet you @ qiuqiu"),tmp; stack<string> s; stringstream ss; ss<<str; while(ss>>tmp) { s.push(tmp); } while(!s.empty()) { cout<<s.top(); s.pop(); if(s.size()!=0) cout<<" "; } return 0; } // 輸出結果: > cd "f:\VScoding\" ; if ($?) { g++ Yqifei.cpp -o Yqifei } ; if ($?) { .\Yqifei } qiuqiu @ you meet to nice