stack::push() - ใส่ข้อมูล
ใส่ element ใหม่ที่ด้านบน (top) ของ stack คัดลอก/ย้ายค่าเข้า underlying container
Syntax
void push(const T& val); // copy
void push(T&& val); // move (C++11)
ตัวอย่าง
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
// Stack (top→bottom): 3, 2, 1
stack::pop() - ลบข้อมูล
ลบ element ด้านบน (top) ออกจาก stack ลด size ลง 1
Syntax
void pop();
⚠️ สำคัญ: pop() ไม่คืนค่า
ต้อง top() อ่านค่าก่อน แล้วค่อย pop()
// ❌ ผิด
int x = st.pop(); // compile error: void return
// ✅ ถูก
int x = st.top();
st.pop();
ตัวอย่างครบ: Push แล้ว Pop คำนวณผลคูณ
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> st;
long long product = 1;
// Push 1..6
for (int i = 1; i <= 6; i++) st.push(i);
cout << "Size: " << st.size() << "\n"; // 6
// Pop ทั้งหมดคำนวณผลคูณ
while (!st.empty()) {
cout << "Top: " << st.top() << ", Size: " << st.size() << "\n";
product *= st.top();
st.pop();
}
cout << "Product: " << product << "\n"; // 720
cout << "Empty: " << st.empty() << "\n"; // 1
return 0;
}
Output
Size: 6 Top: 6, Size: 6 Top: 5, Size: 5 Top: 4, Size: 4 Top: 3, Size: 3 Top: 2, Size: 2 Top: 1, Size: 1 Product: 720 Empty: 1
Complexity
push(): Amortized O(1) (ขึ้นอยู่กับ underlying container)pop(): O(1)
Underlying Container
Default ใช้ deque สามารถเปลี่ยนได้:
stack<int, vector<int>> st_vec; // ใช้ vector
stack<int, list<int>> st_list; // ใช้ list
สรุป
push(val)- ใส่ข้อมูลด้านบน O(1)pop()- ลบข้อมูลด้านบน O(1) **ไม่คืนค่า**- ต้อง
top()ก่อนpop()ถ้าอยากได้ค่า - เช็ค
empty()ก่อน pop/top เพื่อกัน UB