C++ STL之Stack栈

· · 个人记录

C++ 栈

简介

栈的特点

栈是C++中很常用的一种线性数据结构,定义在头文件<stack>中,具有如下特点:

在出栈的过程中,栈顶位置一直在”向下“移动,而栈底一直保持不变。

具体实现

这里,我们主要讲述一下如何使用STL实现栈。

#include <iostream>
#include <stack> 
using namespace std; 

int main()
{
    stack<int> s;
    s.push(1);
    s.push(5);
    s.push(7);

    cout << s.size() << endl;
    while(!s.empty())
    {
        cout << s.top() << " ";
        s.pop();
    }

    return 0;
}

输出:

3
7 5 1

自定义类型:

自定义类型也是很简单的:

#include <iostream>
#include <stack> 
using namespace std; 

struct node
{
    int val;
    node(int _v): val(_v) {}
};

int main()
{
    stack<node> s;
    s.push(node(1));
    s.push(node(5));
    s.push(node(7));

    cout << s.size() << endl;
    while(!s.empty())
    {
        node tmp = s.top();
        s.pop();
        cout << tmp.val << " ";
    }

    return 0;
}

输出同上。

原文刊于我的博客,地址:https://charcai.github.io/2018/06/30/stl-stack.html