STL—stack


一、什么是stack

stack翻译为栈,是STL中实现的一个先进后出的容器,要使用stack,需要添加头文件#include <stack>


二、stack的操作

1.stack的定义

stack<typename> name;

其定义方法和其他的STL容器相同,typename可以是任意基本数据结构或容器

2.stack容器内元素的访问

由于栈(stack)本身就是一种后进先出的数据结构,在STL中的stack只能通过top()来访问栈顶元素
向栈中插入一个元素:s.push(x);

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int> s;
    for (int i = 1; i <= 5; i ++ ) s.push(i);
    
    cout << s.top();
    
    return 0;
}

输出结果:5

3.stack中的函数

(1)push()

s.push(x);把x入栈,时间复杂度为O(1),实例见stack容器内元素的访问

(2)top()

s.top();获得栈顶元素,时间复杂度为O(1),实例见stack容器内元素的访问

(3)pop()

s.pop();用来弹出栈顶元素,时间复杂度为O(1)

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int> s;
    for (int i = 1; i <= 5; i ++ ) s.push(i);
    
    for (int i = 1; i <= 3; i ++ ) s.pop();
    //把 5 4 3 依次弹出
    cout << s.top();
    
    return 0;
}

输出结果为:2

(4)empty()

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

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int> s;
    
    if(s.empty()) cout << "EMPTY" << endl;
    else cout << "NOT EMPTY" << endl;
    
    for (int i = 1; i <= 5; i ++ ) s.push(i);
    
    if(s.empty()) cout << "EMPTY" << endl;
    else cout << "NOT EMPTY" << endl;
    
    return 0;
}

输出结果为:
EMPTY
NOT EMPYTY

(5)size()

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

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int> s;
    for (int i = 1; i <= 5; i ++ ) s.push(i);
    
    cout << s.size();
    
    return 0;
}

输出结果为:5

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值