STL--stack栈的使用

  • 栈的常用操作:
    1.清空clear()
    2.大小size()
    3.判空empty()
    4.入栈push()
    5.出栈pop()
    6.栈顶元素top()
    //出栈入栈和访问元素

  • 注意点:
    在使用pop()和top()函数的时候,需要先判断是否栈为空
    STL中没有清空clear()函数,需要自己编写:

while(!s.empty())//判空
    {
        s.pop();//出栈
    }
  • 代码编写
//北航机试准备2020/3/27
#include<stdio.h>
#include<stack>
using namespace std;

int main()
{
    int i;
    stack<int> s;
    for(i  = 0;i<5;i++)
    {
        //入栈
        s.push(i);
    }
    

    while(!s.empty())//判空
    {
        s.pop();//出栈
    }
    
    //大小
    printf("%d\n",s.size());

    //printf("%d\n",s.top());出现错误

    return 0;
}

发布了71 篇原创文章 · 获赞 36 · 访问量 9443

猜你喜欢

转载自blog.csdn.net/qq_34686440/article/details/105141947