C++ STL-stack使用详解

stack 类是容器适配器,它给予程序员栈的功能——特别是 FILO (先进后出)数据结构。

该类模板表现为底层容器的包装器——只提供特定函数集合。栈从被称作栈顶的容器尾部推弹元素。

一:头文件

#include<stack>

二:定义stack

stack<int>  s;创建一个空的 stack 对象。

stack<int, list<int> >   s1;
stack<int, list<int> >   s2(s1);
利用 s1 ,创建一个以双向链表为底层容器的空堆栈对象 s2 。

 三:基本函数

empty() 堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素

swap()交换元素

四:用法示例

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

int main() {
    int i = 0;
    stack<int> v;
    for (i=0;i<10;++i)
    {
        v.push(i);
        cout << v.top() << "已入栈"<<endl;

    }
    cout << "现在栈的容量" << v.size() << endl;
    for (i=0;i<10;++i)
    {
        cout << v.top() << "准备出栈" << endl;
        v.pop();
    }
    cout << "现在栈的容量" << v.size() << endl;
    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_41785863/article/details/81630730