C++ STL 常用容器之 stack

C++ STL Container--Stack

栈是一种先进后出(LIFO)的数据结构,限制只能在一端完成插入和删除操作,这一端叫做栈顶(top),另一端即为栈底(bottom)。C++ STL(Standrad Template Libarary)中stack容器泛化是使用现成的序列容器来实现的,默认使用双端队列dequeue来实现,也可以使用vector、list等线性结构。
为了严格遵循栈的先进后出原则,stack不提供任何元素的迭代器操作,因此,stack容器不会向外部提供任何可用的前向或反向迭代器类型。

构造

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

构造函数主要有两个参数:class T 指定栈中存储的元素类型, class Container = deque指定底层实现栈的容器类型,默认是双端队列。

    stack<int> S(); //默认底层使用deque实现,创建一个空的堆栈对象
    stack<int, list<int>> S(); //指定使用list<int> 实现栈;

    stack<T> S(const stack&); // 复制构造函数
    list<int> L(2,200);
    stack<int, list<int>> S(L);

栗子:

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

int main()
{
    stack<int> first;
    deque<int> mydeque (2,300);
    stack<int> second (mydeque);
    
    stack<int, vector<int>> third;
    vector<int> myvector (2, 100);
    stack<int, vector<int>> fourth (myvector);
    
    cout << "size of the first stack: " << first.size() << endl;
    cout << "size of the second stack: " << second.size() << endl;
    cout << "size of the third stack: " << third.size() << endl;
    cout << "size of the fourth stack: " << fourth.size() << endl;
    return 0;
    
}

成员函数

stack<int> S1;
stack<int> S2(S1);
/*成员函数原型:
void push(const value_type&x);
void pop();//这两个函数都不会预先检查堆栈满或是空
value_type& top();
bool empty();
int size();
*/

栗子:

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

int main()
{
    stack<int> S;
    for (int i = 0; i < 5; i++) S.push(i);
    cout << S.size() << endl;
    while(!S.empty())
    {
        cout << S.top() << " ";
        S.pop();
    }
    return 0;
}

栗子二:

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

struct Node
{
    int a, b;
    Node (int x, int y)
    {
        a = x; b = y;
    }
};

void printStack(stack<Node> &s)
{
    int i = 0;
    stack<Node> s1(s);
    while(!s1.empty())
    {
        Node p = s1.top();
        cout << "the " << ++i << "-th: ";
        cout << p.a << " " << p.b << endl;
        s1.pop();
    }
}
int main()
{
    stack<Node> mystack;
    mystack.emplace(1,2); //emplace可以将一个元素加入栈中,与push的不同在于,emplace可以直接传入Node的构造函数的参数,并将构造的元素插到栈顶
    mystack.emplace(1,3);
    printStack(mystack);

    stack<Node> my2;
    my2.emplace(2,3);
    my2.emplace(2,1);
    my2.swap(mystack); //swap函数可以交换两个栈的元素
    cout << "mystack:"<<endl;
    printStack(mystack);
    cout << "my2:"<<endl;
    printStack(my2);
    return 0;
}

表1. stack常用成员函数示例

函数原型 复杂度
int size(); O(1)
value_type& top(); O(1)
void pop(); O(1)
void push(const value_type& x); O(1)
bool empty(); O(1)
posted @ 2020-03-26 20:58  CK-A  阅读(114)  评论(0编辑  收藏  举报