源码:

    1. #include<iostream>
    2. #include<stack>
    3. using namespace std;
    4. //栈容器
    5. void test01() {
    6. //特点:先进后出
    7. stack<int>s;
    8. //入栈
    9. s.push(10);
    10. s.push(20);
    11. s.push(30);
    12. s.push(40);
    13. //只要栈不为空,查看栈顶,并执行出栈操作
    14. while (!s.empty()) {
    15. //查看栈顶元素
    16. cout << "栈顶元素为:" << s.top() << endl;
    17. //出栈
    18. s.pop();
    19. }
    20. cout << "栈的大小为:" << s.size() << endl;
    21. }
    22. int main() {
    23. test01();
    24. return 0;
    25. }

    运行结果:
    image.png