ไลบรารีแม่แบบมาตรฐานของภาษาซีพลัสพลัส/stack

จาก testwiki
รุ่นแก้ไขเมื่อ 17:23, 23 มีนาคม 2567 โดย imported>Minorax (method)
(ต่าง) ←รุ่นแก้ไขก่อนหน้า | รุ่นแก้ไขล่าสุด (ต่าง) | รุ่นแก้ไขถัดไป→ (ต่าง)
ไปยังการนำทาง ไปยังการค้นหา

stack เป็นโครงสร้างข้อมูล แบบ LIFO

การใช้งานและประกาศตัวแปร

ต้องนำเข้า header file "stack" โดย #include <stack>

ให้ T คือชนิดข้อมูลใดๆ และ var คือชื่อตัวแปร มีรูปแบบการประกาศตัวแปร stack คือ stack <T> var;

method

push

แม่แบบ:STLdata

pop

แม่แบบ:STLdata

top

แม่แบบ:STLdata

size

แม่แบบ:STLdata

empty

แม่แบบ:STLdata

ตัวอย่างโค้ด

#include <cstdio>
#include <stack>

using namespace std;

struct ST{
    int a, b;
};

int main(){
    stack <int> S;                // []
    S.push(13);                   // [13]
    S.push(12);                   // [13,12]
    S.push(11);                   // [13,12,11]
    S.push(10);                   // [13,12,11,10]
    printf("%d\n", S.top());      // => 10
    S.pop();                      // [13,12,11]
    printf("%d\n", S.size());     // => 3
    while(not S.empty()) S.pop(); // []
    S.pop()                       // => Error
    S.top()                       // => Error
                                  
    ST tmp;                       
    stack <ST> T;                 // []
    tmp.a = 5;                    
    tmp.b = 3;                    
    T.push(tmp);                  // [(5,3)]
    printf("%d\n", T.top().b);    // => 3
    return 0;
}

สารบัญ

แม่แบบ:Stage short stack
แม่แบบ:Stage short queue
แม่แบบ:Stage short priority_queue
แม่แบบ:Stage short deque
แม่แบบ:Stage short vector
แม่แบบ:Stage short map
แม่แบบ:Stage short set