Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

stack::top() ใน C++ STL: เข้าถึงข้อมูลด้านบนของ Stack

stack::top() คืออะไร?

top() เป็น member function ของ std::stack (ใน <stack>) คืน **reference** ไปยัง element ด้านบนสุด (last inserted) ของ stack

Syntax

reference top();
const_reference top() const;

Parameters

ไม่มี parameter

Return Value

  • Reference ไปยัง top element (สามารถอ่าน/เขียนได้)
  • Undefined Behavior ถ้า stack ว่าง → ต้องเช็ค empty() ก่อน

ตัวอย่าง

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

int main() {
    stack<int> st;
    st.push(1);
    st.push(3);
    st.push(5);
    
    cout << "Top: " << st.top() << "\n"; // 5
    
    // แก้ไขค่า top ได้ (เพราะคืน reference)
    st.top() = 10;
    cout << "New top: " << st.top() << "\n"; // 10
    
    // Pop ทั้งหมด
    while (!st.empty()) {
        cout << st.top() << " ";
        st.pop();
    }
    // Output: 10 3 1
    
    return 0;
}

Output

Top: 5
New top: 10
10 3 1

ข้อควรระวัง

  • ❌ st.top() บน empty stack = **Crash/UB**
  • ✅ ต้อง if (!st.empty()) { ... st.top() ... }
  • pop() **ไม่คืนค่า** - ต้อง top() ก่อน pop

Pattern แบบปลอดภัย

while (!st.empty()) {
    auto val = st.top(); // อ่านค่า
    st.pop();            // ลบ
    process(val);
}

สรุป

stack::top() ใช้ดู/แก้ไขค่าด้านบนสุดของ stack O(1) ต้องเช็ค empty() ก่อนใช้เสมอ