C++ - STL中的stack

stack介绍

stack模板类的定义在<stack>头文件中。栈是一种容器适配器,特别为后入先出而(LIFO )设计的一种数据结构

2-1P913101Q4T2.jpg

栈有两个参数。

template < class T, class Container = deque<T> > class stack;

参数:

  • T: 元素类型
  • Container: 被用于存储和访问元素的的类型

栈实现了容器适配器,这是用了一个封装了的类作为它的特定容器,提供了一组成员函数去访问他的元素,元素从栈的尾部插入和取出元素。基础的容器可能是任何标准的容器类,和一些其他特殊设计的模板类一样,必须提供一些基本的操作,如下

back() 
push_back() 
pop_back()

标准的容器类模板vector, dequelist都满足这些要求,所以都可以使用,默认情况下,如果没有容器类被指定成为一个提别的stack类,标准的容器类模板就是deque队列。stack类定义如下:

namespace std
{
template <class T, class Container = deque<T>>
class stack
{
public:
    typedef Container                                container_type;
    typedef typename container_type::value_type      value_type;
    typedef typename container_type::reference       reference;
    typedef typename container_type::const_reference const_reference;
    typedef typename container_type::size_type       size_type;

protected:
    container_type c;

public:
    stack() = default;
    ~stack() = default;

    stack(const stack& q) = default;
    stack(stack&& q) = default;

    stack& operator=(const stack& q) = default;
    stack& operator=(stack&& q) = default;

    explicit stack(const container_type& c);
    explicit stack(container_type&& c);
    template <class Alloc> explicit stack(const Alloc& a);
    template <class Alloc> stack(const container_type& c, const Alloc& a);
    template <class Alloc> stack(container_type&& c, const Alloc& a);
    template <class Alloc> stack(const stack& c, const Alloc& a);
    template <class Alloc> stack(stack&& c, const Alloc& a);

    bool empty() const;
    size_type size() const;
    reference top();
    const_reference top() const;

    void push(const value_type& x);
    void push(value_type&& x);
    template <class... Args> reference emplace(Args&&... args); // reference in C++17
    void pop();

    void swap(stack& c) noexcept(is_nothrow_swappable_v<Container>)
};

成员函数

  • 构造函数
stack() = default; //  默认构造函数
stack(const stack& q) = default; // 默认复制构造函数
stack(stack&& q) = default;

explicit stack(const container_type& c); // Copy-constructs
explicit stack(container_type&& c);  // Move-constructs the underlying container c with std::move(cont)

 // Constructs the underlying container using alloc as allocator, as if by c(alloc).
template <class Alloc> explicit stack(const Alloc& a);
template <class Alloc> stack(const container_type& c, const Alloc& a);
template <class Alloc> stack(container_type&& c, const Alloc& a);
template <class Alloc> stack(const stack& c, const Alloc& a);
template <class Alloc> stack(stack&& c, const Alloc& a);

简单使用

#include <stack>
#include <deque>
#include <iostream>
 
int main()
{
    std::stack<int> c1;
    c1.push(5);
    std::cout << c1.size() << '\n';
 
    std::stack<int> c2(c1);
    std::cout << c2.size() << '\n';
 
    std::deque<int> deq {3, 1, 4, 1, 5};
    std::stack<int> c3(deq);
    std::cout << c3.size() << '\n';
}

输出

1
1
5

也可以提供提前声明使用命名空间std

#include <stack>
#include <deque>
#include <iostream>
using namespace std;
 
int main()
{
    stack<int> c1;
    c1.push(5);
    cout << c1.size() << '\n';
 
    stack<int> c2(c1);
    cout << c2.size() << '\n';
 
    deque<int> deq {3, 1, 4, 1, 5};
    stack<int> c3(deq);
    cout << c3.size() << '\n';
}
  • 访问元素
std::stack<T,Container>::top

reference top(); // 顶元素
const_reference top() const;

bool empty() const; // 是否为空
size_type size() const; // 容器元素的个数

使用top()函数返回栈顶的元素,也可以理解为最近push的元素

#include <stack>
#include <iostream>
 
int main()
{
    std::stack<int>   s;
 
    s.push( 2 );
    s.push( 6 );
    s.push( 51 );

    std::cout << "empty: " << s.empty() << "\n";
    std::cout << s.size() << " elements on stack\n";
    std::cout << "Top element: "
          << s.top()         // Leaves element on stack
          << "\n";
    std::cout << s.size() << " elements on stack\n";
    s.pop();
    std::cout << s.size() << " elements on stack\n";
    std::cout << "Top element: " << s.top() << "\n";
 
    return 0;
}

运行输出

empty: 0
3 elements on stack
Top element: 51
3 elements on stack
2 elements on stack
Top element: 6
  • 修改容器元素
void push(const value_type& x); // 入栈元素
void push(value_type&& x);

// This function is used to insert a new element into the stack container
// the new element is added on top of the stack.
template <class... Args> reference emplace(Args&&... args); // reference in C++17
void pop(); // 去除栈顶元素

void swap(stack& c) noexcept(is_nothrow_swappable_v<Container>)

简单使用pushpop

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

int main(int argc, const char * argv[]) {
    stack<int> mystack;

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

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

    return 0;
}

运行输出

pop element:
 4 3 2 1 0

使用emplace插入元素

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

int main() {
    stack<int> mystack;
    mystack.emplace(1);
    mystack.emplace(2);
    mystack.emplace(3);
    mystack.emplace(4);
    mystack.emplace(5);
    mystack.emplace(6);
    // stack becomes 1, 2, 3, 4, 5, 6

    // printing the stack
    cout << "mystack = ";
    while (!mystack.empty()) {
        cout << mystack.top() << " ";
        mystack.pop();
    }
    return 0;
} 

运行输出

mystack = 6 5 4 3 2 1
  • 交换stack容器元素
// This function is used to swap the contents of one stack with another stack of same type and size.
void swap(stack& c) noexcept(is_nothrow_swappable_v<Container>)

简单使用

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

int main()
{
    // stack container declaration
    stack<int> mystack1;
    stack<int> mystack2;

    // pushing elements into first stack
    mystack1.push(1);
    mystack1.push(2);
    mystack1.push(3);
    mystack1.push(4);

    // pushing elements into 2nd stack
    mystack2.push(3);
    mystack2.push(5);
    mystack2.push(7);
    mystack2.push(9);

    // using swap() function to swap elements of stacks
    mystack1.swap(mystack2);

    // printing the first stack
    cout<<"mystack1 = ";
    while (!mystack1.empty()) {
        cout<<mystack1.top()<<" ";
        mystack1.pop();
    }

    // printing the second stack
    cout<<endl<<"mystack2 = ";
    while (!mystack2.empty()) {
        cout<<mystack2.top()<<" ";
        mystack2.pop();
    }
    return 0;
}

运行输出

mystack1 = 9 7 5 3 
mystack2 = 4 3 2 1 

使用场景

  • 删除指定位置元素
#include <iostream>
#include <stack>

using namespace std;

// Deletes middle of stack of size
// n. Curr is current item number
void deleteMid(stack<char> &st, int n,
               int curr=0)
{
    // If stack is empty or all items
    // are traversed
    if (st.empty() || curr == n)
        return;

    // Remove current item
    int x = st.top();
    st.pop();

    // Remove other items
    deleteMid(st, n, curr+1);

    // Put all items back except middle
    if (curr != (n - 1))
        st.push(x);
}

//Driver function to test above functions
int main()
{
    stack<char> st;

    //push elements into the stack
    st.push('1');
    st.push('2');
    st.push('3');
    st.push('4');
    st.push('5');
    st.push('6');
    st.push('7');

    deleteMid(st, 4);

    // Printing stack after deletion
    // of middle.
    while (!st.empty())
    {
        char p=st.top();
        st.pop();
        cout << p << " ";
    }
    return 0;
}

运行输出

7 6 5 3 2 1

更多内容可以参考stack-data-structure

参考

stack

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容

  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 9,516评论 1 51
  • STL部分 1.STL为什么广泛被使用 C++ STL 之所以得到广泛的赞誉,也被很多人使用,不只是提供了像vec...
    杰伦哎呦哎呦阅读 4,321评论 0 9
  • 容器的概念所谓STL容器,即是将最常运用的一些数据结构(data structures)实现出来。容器是指容纳特定...
    饭饭H阅读 381评论 0 0
  • STL(标准模板库),是目前C++内置支持的library。它的底层利用了C++类模板和函数模板的机制,由三大部分...
    岁与禾阅读 39,003评论 3 133
  • 蚂蚁 这是一群勤劳的精灵 默默地生存 默默地走在黄昏黎明 偶遇一粒馍渣 不是享用而是去寻找同伴 暴...
    黄梅枝阅读 1,100评论 26 47