STL学习记录(十五):Stack

STL中的特殊容器Stack

准确来说Stack是容器适配器类型,与我们数据结构中所学的概念一样这种容器的特性就是Last Input First Output。该容器通过push、
pop方法对栈头的元素进行操作。主要的成员函数如下:

成员函数说明
empty( )判断栈是否为空
size( )返回栈的大小
push( val )将元素加入到栈首
pop( )取出栈中的首元素
top( )访问栈首元素
emplace( val )将元素加入到栈首,元素在作为参数传递的时候通过自身构造函数构造
swap( stc )将stc栈进行元素交换


代码示例:

// stack::swap stack::size
#include <iostream>       
#include <stack>          
using namespace std;

int main ()
{
    stack<int> foo,bar;
    foo.push (10); foo.push(20); foo.push(30);
    bar.push (111); bar.push(222);

    foo.swap(bar);

    cout << "size of foo: " << foo.size() << endl;
    cout << "size of bar: " << bar.size() << endl;

    return 0;
}
// stack::push/pop
#include <iostream>       
#include <stack>
using namespace std;          

int main ()
{
    stack<int> mystack;

    for (int i=0; i<5; ++i) mystack.push(i);

    cout << "Popping out elements...";
    while (!mystack.empty())
    {
         cout << ' ' << mystack.top();
         mystack.pop();
    }
    cout << endl;

    return 0;
}
// stack::emplace
#include <iostream>       
#include <stack>          
#include <string>   
using namespace std;      

int main ()
{
    stack<string> mystack;

    mystack.emplace ("First sentence");
    mystack.emplace ("Second sentence");

    cout << "mystack contains:\n";
    while (!mystack.empty())
    {
        cout << mystack.top() << endl;
        mystack.pop();
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值