堆疊
簡介
按照後進先出(LIFO, Last In First Out)運作,只允許從容器頂端(top)進行插入(push)和移除(pop)。

就像一層一層疊起來的書本,只能從上面放,上面取(不要調皮)。
標頭檔
宣告
type 可為 int, char, string…,sta可為任意名字。
常用操作
| 函數 |
描述 |
| push() |
從堆疊頂端插入一元素 |
| pop() |
從堆疊頂端移除一元素 |
| top() |
回傳頂端元素 |
| empty() |
回傳堆疊是否為空 |
| size() |
回傳堆疊中有幾個元素 |
範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> #include <stack> using namespace std;
int main(){ stack<int> sta; for(int i = 0; i < 5; ++i) sta.push(i); sta.pop(); cout << "目前頂端元素為 " << sta.top() << "\n"; cout << "是否為空 " << sta.empty() << "\n"; cout << "目前元素個數為 " << sta.size() << "\n"; while(!sta.empty()){ sta.pop(); } cout << "是否為空 " << sta.empty() << "\n";
return 0; }
|
目前頂端元素為 3
是否為空 0
目前元素個數為 4
是否為空 1
參考資料:cplusplus.com