C++STL-stack

一.基础概念

相当于数据结构里面栈,后进先出,从尾部插入,从尾部删除。

二.基础用法 

1.stack对象创建

 1. 默认构造函数stack<int> stk1;
2. 拷贝构造函数stack<int> stk2(stk1);

2.stack赋值操作

    stack<int> stk1;
    stack<int> stk2;

    stk1 = stk2;

3.stack入栈操作

    stack<int> stk;

    stk.push(5);     // 5
    stk.push(4);     // 5 4
    stk.push(3);     // 5 4 3
    stk.push(2);     // 5 4 3 2
    stk.push(1);     // 5 4 3 2 1

4.stack获取栈顶元素

    stack<int> stk;
    stk.push(5);    cout << stk.top() << endl;   // 5
    stk.push(4);    cout << stk.top() << endl;   // 4
    stk.push(3);    cout << stk.top() << endl;   // 3
    stk.push(2);    cout << stk.top() << endl;   // 2
    stk.push(1);    cout << stk.top() << endl;   // 1

5.stack出栈操作

    stack<int> stk;
    stk.push(5);    cout << stk.top() << endl;   // 5
    stk.push(4);    cout << stk.top() << endl;   // 4
    stk.push(3);    cout << stk.top() << endl;   // 3
    stk.push(2);    cout << stk.top() << endl;   // 2
    stk.push(1);    cout << stk.top() << endl;   // 1

    stk.pop();      cout << stk.top() << endl;   // 2
    stk.pop();      cout << stk.top() << endl;   // 3
    stk.pop();      cout << stk.top() << endl;   // 4
    stk.pop();      cout << stk.top() << endl;   // 5
    stk.pop();      cout << stk.top() << endl;   // 为空会报错

5.stack大小操作

 stk.empty()判断是否为空
stk.size()查看这个栈里有多少元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值