STL queue的使用

来源:互联网 发布:为什么四川美女多 知乎 编辑:程序博客网 时间:2024/05/21 22:39

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

与stack模板类很相似,queue模板类也需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque类型。

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

queue<int> q1;
queue<double> q2;

queue的基本操作有:

入队,如例:q.push(x); 将x接到队列的末端。

出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。

访问队首元素,如例:q.front(),即最早被压入队列的元素。

访问队尾元素,如例:q.back(),即最后被压入队列的元素。

判断队列空,如例:q.empty(),当队列空时,返回true。

访问队列中的元素个数,如例:q.size()


关于队列的题目:

① HDU 1022  


#include<iostream>#include<string>#include<stack>using namespace std;int main(){    int n;    while(cin>>n){        string s1,s2,s3[15];//记录进出轨的操作        cin>>s1>>s2;        stack<char> a;//缓冲轨        int i=0,j=0,k=0;        while(i<s1.size()){            a.push(s1[i]);            s3[k++]="in";//每次必须先进轨,进行调头            while(j<s2.size()){                if(a.size()&&a.top()==s2[j]){//非空且相等                    a.pop();//出轨                    ++j;//比较下一个                    s3[k++]="out";//记录出轨操作                }                else break;//else跳出比较循环            }            ++i;//下一列车进轨        }        if(!a.size()) {//if(缓冲轨为空则可以完成)"Yes"            cout<<"Yes."<<endl;            for(i=0;i<k;i++)                cout<<s3[i]<<endl;            cout<<"FINISH"<<endl;        }        else {//不能完成"No"            cout<<"No."<<endl;            cout<<"FINISH"<<endl;        }    }    return 0;}

② 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
原创粉丝点击