stack::empty() - ตรวจสอบว่าว่างหรือไม่
คืน true ถ้า stack ไม่มี element (size = 0), false ถ้ามีข้อมูล
Syntax
bool empty() const;
ตัวอย่าง
stack<int> st1;
st1.push(1); st1.push(2); st1.push(3);
cout << st1.empty(); // 0 (false)
stack<int> st2;
cout << st2.empty(); // 1 (true)
stack::size() - จำนวนข้อมูล
คืนจำนวน elements ใน stack (unsigned integer type)
Syntax
size_type size() const;
ตัวอย่าง
stack<int> st;
st.push(1); st.push(2); st.push(3);
cout << st.size(); // 3
stack<int> empty_st;
cout << empty_st.size(); // 0
ตัวอย่างรวม: ใช้ empty() และ size() ควบคุม Loop
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> st;
for (int i = 1; i <= 6; i++) st.push(i);
// Pattern 1: ใช้ empty()
long long prod1 = 1;
while (!st.empty()) {
prod1 *= st.top();
st.pop();
}
cout << "Product (empty): " << prod1 << "\n"; // 720
// Push ใหม่
for (int i = 1; i <= 6; i++) st.push(i);
// Pattern 2: ใช้ size()
long long prod2 = 1;
while (st.size() > 0) {
prod2 *= st.top();
st.pop();
}
cout << "Product (size): " << prod2 << "\n"; // 720
return 0;
}
Output
Product (empty): 720 Product (size): 720
Complexity
- ทั้งคู่ O(1) - เพียงดึงค่า size จาก underlying container
Best Practices
- ใช้
empty()แทนsize() == 0(semantic ชัดเจนกว่า บาง container size() อาจเป็น O(n) แต่ stack/deque/list/vector ล้วน O(1)) - **เช็ค empty() ก่อน top()/pop() ทุกครั้ง**
- C++20: ใช้
std::ssize(st)ได้ signed size
สรุป
| Function | Return | Use Case |
|---|---|---|
empty() | bool | เช็คว่าว่างก่อน pop/top, loop condition |
size() | size_type | รู้จำนวน element, reserve, debug |
ทั้งคู่ O(1) เป็นฟังก์ชันพื้นฐานที่ต้องใช้ให้ถูกต้องเพื่อป้องกัน Undefined Behavior