C++ Stack Implementation: std::stack Guide

In C++, the std::stack template class in the STL can be used to implement a stack. The std::stack class is a container adapter, which implements the functionality of a stack based on other sequence containers like std::vector, std::deque, and std::list.

Below is an example code implementing a stack using std::stack.

#include <iostream>
#include <stack>

int main() {
    std::stack<int> myStack;

    // 将元素压入栈
    myStack.push(1);
    myStack.push(2);
    myStack.push(3);

    // 访问栈顶元素
    std::cout << "栈顶元素:" << myStack.top() << std::endl;

    // 弹出栈顶元素
    myStack.pop();
    std::cout << "弹出栈顶元素后的栈顶元素:" << myStack.top() << std::endl;

    // 检查栈是否为空
    if (myStack.empty()) {
        std::cout << "栈为空" << std::endl;
    } else {
        std::cout << "栈不为空" << std::endl;
    }

    // 获取栈的大小
    std::cout << "栈的大小:" << myStack.size() << std::endl;

    return 0;
}

In the example above, a stack of integers is created using the statement std::stack myStack;. The function myStack.push(1); pushes the element 1 onto the stack. The function myStack.top() returns the element at the top of the stack. The function myStack.pop() removes the element at the top of the stack. The function myStack.empty() checks if the stack is empty. The function myStack.size() gets the size of the stack.

bannerAds