c++ stack 教學 | 用法及範例

c++ stack 教學

建立 stack

  • #include <stack> : 引入 stack
  • stack<dataType> st : 宣告

常用功能

  • st.push(val) : 將元素(val) 加到 stack
  • st.pop() : 將最上面的元素移除
  • st.top() : 回傳最上面的值
  • st.size() : stack 的大小
  • st.empty() : 判斷 stack 是不是空的

注意事項

  • .pop() 只會移除元素,不會回傳值;若需要值,需先用 .top() 取得。
  • 如果對空的 stack 呼叫 .pop().top() 會造成 segmentation fault。
  • stack 不提供 iterator,因此無法直接遍歷或存取中間元素,只能透過 top 操作最上面的元素。

使用範例 :

#include <iostream>
#include <stack>
using namespace std;

int main(){
    
    stack<int> st;

    st.push(1);             // st = {1}
    st.push(5);             // st = {1, 5}
    st.push(3);             // st = {1, 5, 3}
    
    cout<<st.top()<<"\n";   // 3
    cout<<st.size()<<"\n";  // 3
    
    st.pop();               // st = {1, 5}
    cout<<st.top()<<"\n";   // 5
    cout<<st.size()<<"\n";  // 2
    
    cout<<st.empty()<<"\n";  // 0 
}