stack的常见用法

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

1、stack的定义

【头文件】

#include<stack>

using namespace;

定义方法与其他容器相同,typename可以任意基本类型数据类型或容器

stack<typename> name;

2、stack容器内元素的访问

由于栈(stack)本身就是一种后进先出的数据结构

在STL的stack中只能通过top()来访问栈顶元素

#include<utility>
#include<iostream>
#include<stdio.h>
#include<string>
#include<algorithm>
#include<map>
#include<vector>
#include<stack>
using namespace std;
int main()
{
    stack<int> st;
    for(int i=1;i<=5;i++)
    {
        st.push(i);
    }
    printf("%d\n",st.pop());
    return 0;
}

3、stack常用函数

扫描二维码关注公众号,回复: 2946589 查看本文章

①push()

入栈

②top()

获得栈顶元素

③pop()

弹出栈顶元素

#include<utility>
#include<iostream>
#include<stdio.h>
#include<string>
#include<algorithm>
#include<map>
#include<vector>
#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();
    }
    printf("%d\n",st.pop());
    return 0;
}

④empty()

可以检测stack内是否为空,返回true为空,返回false为非空

⑥size()

返回stack内元素的个数

4、stack的常见用途

stack常用来模拟一些递归,防止程序对栈内存的限制而导致程序出错

一般来说

程序的栈内存空间很小

对有些题目来说

如果用普通的函数来进行递归

一旦递归层数过深

则会导致程序运行崩溃

如果用栈来模拟递归算法的实现

可以避免这一方面的问题

知识点来自于《算法笔记》

猜你喜欢

转载自blog.csdn.net/qq_42232118/article/details/82080776