C++:queue队列的使用

2025-05-31 06:16:44

1、queue应用例程:#include <queue>#include <iostream>using namespace std;int 罪焐芡拂main(){ queue<int> myQ; for(int i=0; i<10; i++) myQ.push(i); cout<<"myQ size is: "<<myQ.size()<<endl; for(int i=0; i<myQ.size(); i++) { cout << myQ.front()<<endl; myQ.pop(); } cout<<"myQ size is: "<<myQ.size()<<endl; return 0;}

C++:queue队列的使用

2、什献垴淄睬么是队列?队列是一种特殊的线性表,特殊之处在于:它只允许在表的前端进行删除操作,只允许在表的后端进行插入操作;队列是一种操作受限制的线性表;进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。队列的数据元素又称为队列元素。在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出(FIFO—first in first out)线性表。

C++:queue队列的使用

3、顺序队列:建立顺序队列结构必须为其静态分配或动态申请一片连续的存储空间,并设置两个指针进行管理。一个是队头指针front,它指向队头元素;另一个是队尾指针rear,它指向下一个入队元素的存储位置,如图所示:

C++:queue队列的使用

4、C++中的queue:queue是STL的队列,有FIFO的特性。①队列头文件:#include <queue>②queue模板类:需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque类型。定义queue对象的示例代码如下:queue<int> q1;queue<double> q2;queue<Point> q3;

C++:queue队列的使用

5、queue的基本操作有:入队,如例:q.push(x); 将x接到队列的末端。出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。访问队首元素,如例:q.front(),即最早被压入队列的元素。访问队尾元素,如例:q.back(),即最后被压入队列的元素。判断队列空,如例:q.empty(),当队列空时,返回true。访问队列中的元素个数,如例:q.size()

C++:queue队列的使用

6、queue的应用:#include 争犸禀淫"stdafx.h"#include <queue>#include <iostream>#i荏鱿胫协nclude <string>using namespace std;void test_empty(){ queue<int> myqueue; int sum (0); for (int i=1;i<=10;i++) myqueue.push(i); while (!myqueue.empty()) { sum += myqueue.front(); myqueue.pop(); } cout << "total: " << sum << endl;}void test_pop(){ queue<int> myqueue; int myint; cout << "\nPlease enter some integers (enter 0 to end):\n"; do { cin >> myint; myqueue.push (myint); } while (myint); cout << "myqueue contains: "; while (!myqueue.empty()) { cout << " " << myqueue.front(); myqueue.pop(); }}void test_size(){ queue<int> myints; cout << "0. size: " << (int) myints.size() << endl; for (int i=0; i<5; i++) myints.push(i); cout << "1. size: " << (int) myints.size() << endl; myints.pop(); cout << "2. size: " << (int) myints.size() << endl;}int main(){ test_empty(); cout<<"\n***********************************************\n"; test_size(); cout<<"\n***********************************************\n"; test_pop(); cout<<"\n***********************************************\n"; queue<string> q; // insert three elements into the queue q.push("These "); q.push("are "); q.push("more than "); //cout << "number of elements in the queue: " << q.size()<< endl; // read and print two elements from the queue cout << q.front(); q.pop(); cout << q.front(); q.pop(); //cout << "number of elements in the queue: " << q.size()<< endl; // insert two new elements q.push("four "); q.push("words!"); // skip one element q.pop(); // read and print two elements cout << q.front(); q.pop(); cout << q.front() << endl; q.pop(); cout << "number of elements in the queue: " << q.size()<< endl; return 0;}

C++:queue队列的使用
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢