STL系列之queue 单向队列解析

来源:互联网 发布:福州seo顾问 编辑:程序博客网 时间:2024/05/14 13:33

queue单向队列与有点类似,一个是在同一端存取数据,另一个是在一端存入数据,另一端取出数据。单向队列中的数据是先进先出(First In First Out,FIFO)。在STL中,单向队列也是以别的容器作为底部结构,再将接口改变,使之符合单向队列的特性就可以了。单向队列一共6个常用函数(front()、back()、push()、pop()、empty()、size()



由于queue只是进一步封装别的数据结构,并提供自己的接口,所以代码非常简洁,如果不指定容器,默认是用deque来作为其底层数据结构的。下面给出单向队列的使用范例:

[cpp] view plain copy
  1. //单向队列 queue支持 empty() size() front() back() push() pop()  
  2. #include <queue>  
  3. #include <vector>  
  4. #include <list>  
  5. #include <cstdio>  
  6. using namespace std;  
  7.   
  8. int main()  
  9. {  
  10.     //可以使用list作为单向队列的容器,默认是使用deque的。  
  11.     queue<int, list<int>> a;  
  12.     queue<int>        b;  
  13.     int i;  
  14.   
  15.     //压入数据  
  16.     for (i = 0; i < 10; i++)  
  17.     {  
  18.         a.push(i);  
  19.         b.push(i);  
  20.     }  
  21.   
  22.     //单向队列的大小  
  23.     printf("%d %d\n", a.size(), b.size());  
  24.   
  25.     //队列头和队列尾  
  26.     printf("%d %d\n", a.front(), a.back());  
  27.     printf("%d %d\n", b.front(), b.back());  
  28.   
  29.     //取单向队列项数据并将数据移出单向队列  
  30.     while (!a.empty())  
  31.     {  
  32.         printf("%d ", a.front());  
  33.         a.pop();  
  34.     }  
  35.     putchar('\n');  
  36.   
  37.     while (!b.empty())  
  38.     {  
  39.         printf("%d ", b.front());  
  40.         b.pop();  
  41.     }  
  42.     putchar('\n');  
  43.     return 0;  
  44. }  

0 0
原创粉丝点击