绪:看程序遇到queue队列的使用方法;下面通过一个例程来简要概述一下queue队列的知识点:什么是队列;顺序队列;C++:queue队列的用法;模板类;
工具/原料
方法/步骤
1queue应用例程:#include #include using namespace std;int main(){ queue myQ; for(int i=0; i<10; i++) myQ.push(i); cout<<'myQ size is: '<
2什么是队列?队列是一种特殊的线性表,特殊之处在于:它只允许在表的前端进行删除操作,只允许在表的后端进行插入操作;队列是一种操作受限制的线性表;进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。队列的数据元素又称为队列元素。在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出(FIFO—first in first out)线性表。
3顺序队列:建立顺序队列结构必须为其静态分配或动态申请一片连续的存储空间,并设置两个指针进行管理。一个是队头指针front,它指向队头元素;另一个是队尾指针rear,它指向下一个入队元素的存储位置,如图所示:
4C++中的queue:queue是STL的队列,有FIFO的特性。①队列头文件:#include ②queue模板类:需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque类型。定义queue对象的示例代码如下:queue q1;queue q2;queue q3;
5queue的基本操作有:入队,如例:q.push(x); 将x接到队列的末端。出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。访问队首元素,如例:q.front(),即最早被压入队列的元素。访问队尾元素,如例:q.back(),即最后被压入队列的元素。判断队列空,如例:q.empty(),当队列空时,返回true。访问队列中的元素个数,如例:q.size()
6queue的应用:#include 'stdafx.h' #include #include #include using namespace std; void test_empty() { queue 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 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 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 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;}
注意事项
2q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。