STL stack的使用

来源:互联网 发布:c4d r17 mac下载 编辑:程序博客网 时间:2024/05/17 08:27

stack

stack模板类的定义在<stack>头文件中。

stack模板类需要两个模板参数,一个是元素类型,一个容器类型,但只有元素类型是必要的,在不指定容器类型时,默认的容器类型为deque。

定义stack对象的示例代码如下:

stack<int> s1;
stack<string> s2;

stack的基本操作有:

入栈,如例:s.push(x);

出栈,如例:s.pop();注意,出栈操作只是删除栈顶元素,并不返回该元素。

访问栈顶,如例:s.top()

判断栈空,如例:s.empty(),当栈空时,返回true。

访问栈中的元素个数,如例:s.size()

HDU 1702

#include<iostream>#include<string.h>#include<stack>#include<queue>using namespace std;void que(int n){    int a;    char str[5];    queue <int> q;    while(n--)    {        scanf("%s",str);        if(!strcmp(str,"IN"))        {            scanf("%d",&a);            q.push(a);        }        else        {            if(q.empty())            {                printf("None\n");            }            else            {                printf("%d\n",q.front());                q.pop();            }        }    }    while(!q.empty())    {        q.pop();    }}void sta(int n){    int a;    char str[5];    stack<int> s;    while(n--)    {        scanf("%s",str);        if(!strcmp(str,"IN"))        {            scanf("%d",&a);            s.push(a);        }        else        {            if(s.empty())            {                printf("None\n");            }            else            {                printf("%d\n",s.top());                s.pop();            }        }    }    while(!s.empty())    {        s.pop();    }}int main(){    int t,n,i,j;    char s1[6];    scanf("%de",&t);    while(t--)    {        scanf("%d%s",&n,s1);        if(!strcmp(s1,"FIFO"))        {            que(n);        }        else        {            sta(n);        }    }    return 0;} 


0 0
原创粉丝点击