Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

stack::top() trong C++ STL

stack::top() trả về tham chiếu đến phần tử đỉnh stack (phần tử được push gần nhất).

Cú pháp

stack_name.top();

Ví dụ

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

int main() {
    stack<int> st;
    st.push(1); st.push(2); st.push(3); st.push(4);
    cout << "Top: " << st.top() << endl; // 4
    while (!st.empty()) {
        cout << st.top() << " ";
        st.pop();
    }
    return 0;
}

Đầu ra

Top: 4
4 3 2 1