zoukankan      html  css  js  c++  java
  • 算法笔记--标准模板库STL--stack

    stack的常见用法

    stack翻译为栈,是STL中实现的一个后进先出的容器

    头文件

    #include<stack>
    using namespace std;
    

    stack的定义

    stack<typename> name;
    

    stack容器内元素的访问

    只能通过top()来访问栈顶元素

    #include<iostream>
    #include<stack>
    using namespace std;
    
    int main(){
        stack<int> st;
        for(int i = 1; i <= 5; i++)
            st.push(i);
    
        printf("%d", st.top());	// 5
    
        return 0;
    }
    
    

    stack常用函数

    push( )

    push(x) 将x入栈,时间复杂度为O(1)

    top( )

    top( ) 访问栈顶元素,时间复杂度为O(1)

    pop( )

    pop( ) 用以弹出栈顶元素,时间复杂度为O(1)

    #include<iostream>
    #include<stack>
    using namespace std;
    
    int main(){
        stack<int> st;
        for(int i = 1; i <= 5; i++)
            st.push(i);
    
        for(int i = 1; i <= 3; i++)
            st.pop();               // 出栈3次
    
        printf("%d", st.top());     // 2
    
        return 0;
    }
    

    empty( )

    empty( ) 可以检测stack内是否为空,空返回true,非空返回false,时间复杂度为O(1)

    size( )

    size( ) 返回stack内元素个数,时间复杂度为O(1)

    #include<iostream>
    #include<stack>
    using namespace std;
    
    int main(){
        stack<int> st;
        for(int i = 1; i <= 5; i++)
            st.push(i);
    
        for(int i = 1; i <= 3; i++)
            st.pop();               // 出栈3次
    
        st.empty() ? printf("Empty
    ") : printf("No Empty
    ");
    
        printf("%d
    ", st.size());
        printf("%d", st.top());
    
        return 0;
    }
    
    No Empty
    2
    2
    

    stack的常见用途

    • 用来模拟实现一些递归,防止程序对栈内存的限制而导致程序运行错误

    Write by Gqq

  • 相关阅读:
    在HTML文件中加载js
    HTML表单的问题
    HTML自动换行的问题
    HTML的结束标签问题
    数据库基本知识
    PHP中数据库的连接
    2014年7月
    3.2版本视频讲解知识点
    2014年7月
    选项卡
  • 原文地址:https://www.cnblogs.com/zgqcn/p/12588428.html
Copyright © 2011-2022 走看看