STL之queue容器

来源:互联网 发布:淘宝开店一定要交保证金吗 编辑:程序博客网 时间:2024/05/21 02:21

1 .c++队列queue模板类的定义在<queue>头文件中,queue模板类需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque 类型。queue所有元素的进出都必须符合”先进先出”的条件,只有queue的顶端元素,才有机会被外界取用。所以queue不提供遍历功能,也不提供迭代器。

C++队列Queue是一种容器适配器,它给予一种先进先出(FIFO)的数据结构。

如图:
这里写图片描述

queue容器的常用操作有:queue<T> queT;//queue采用模板类实现,queue对象的默认构造形式:queue(const queue &que);//拷贝构造函数push(elem);//往队尾添加元素pop();//从队头移除第一个元素back();//返回最后一个元素front();//返回第一个元素queue& operator=(const queue &que);//重载等号操作符empty();//判断队列是否为空size();//返回队列的大小------------------------------------------示例: /** 存放普通的数据类型 **/#include<iostream>#include <queue>#include <stdlib.h>using namespace std;void test00(){    queue<int> q;    queue<int> q1;    q.push(1);    q.push(3);    q.push(5);    q.push(7);    q.push(9);    cout<<q.size()<<endl;   //获取队列q的大小    cout<<q.front()<<endl;  //获取对头元素    cout<<q.back()<<endl;   //获取队尾元素    q1 = q;                 //赋值操作    cout<<q1.size()<<endl;  //获取队列q1的大小    while (!q.empty())    {         cout<<q.front()<<" ";         q.pop();    }}int main(){    test00();    system("pause");    return 0;}结果:51951   3   5   7   9------------------------------------------示例: /** 存放自定义的数据类型 **/#include<iostream>#include <queue>#include <string>#include <stdlib.h>using namespace std;class People{public:    People(string name,int age)    {        this->mName = name;        this->mAge = age;    }    People(){}    ~People(){}public:    string mName;    int mAge;};void test00(){    queue<People> p;    p.push(People("aaa",11));    p.push(People("bbb",22));    p.push(People("ccc",33));    p.push(People("ddd",44));    cout<<"p.size() = "<<p.size()<<endl;    while (p.size() > 0)    {        cout<<p.front().mName<<" "<<p.front().mAge<<endl;        p.pop();    }}int main(){    test00();    system("pause");    return 0;}结果:p.size() = 4aaa     11bbb     22ccc     33ddd     44------------------------------------------示例: /** 存放自定义的数据类型指针变量 **/#include<iostream>#include <queue>#include <string>#include <stdlib.h>using namespace std;class People{public:    People(string name,int age)    {        this->mName = name;        this->mAge = age;    }    People(){}    ~People(){}public:    string mName;    int mAge;};void test00(){     //在堆区为队列分配内存空间,将其存放在堆上    queue<People*> *p = new queue<People *>;    p->push(new People("aaa",11));    p->push(new People("bbb",22));    p->push(new People("ccc",33));    p->push(new People("ddd",44));    cout<<"p->size() = "<<p->size()<<endl;    while (!p->empty())    {        People *pTr = p->front();        cout<<p->front()->mName<<" "<<p->front()->mAge<<endl;        p->pop();        if (pTr != NULL)        {            delete pTr;            pTr = NULL;        }    }}int main(){    test00();    system("pause");    return 0;}结果:p.size() = 4aaa     11bbb     22ccc     33ddd     44