#include<queue> 【c++】

来源:互联网 发布:淘宝店铺怎么优化标题 编辑:程序博客网 时间:2024/05/02 01:21
#include <iostream>
#include <queue>
using namespace std; //这几个头文件必不可少

int main()
{
queue<类型(如int)> q; //使用前需定义一个queue变量,且定义时已经初始化
while(!q.empty()) q.pop(); //重复使用时,用这个初始化
q.push(1); //进队列
q.pop(); //出队列
int v=q.front(); //得到队首的值
int s=q.size(); //得到队列里元素个数

return 0;
}
其它概述:
使用queue之前,要先利用构造函数一个队列对象,才可以进行元素的入队,出队,取队首和队尾等操作;
(1).queue() queue<int> q; 或者 queue<int>Q[10000];
(2).queue(const queue&) 复制构造函数 例如:用一行代码利用queue对象q1,创建一个以双向链表为底层容器的queue对象q2queue<int,list<int>>q1;queue<int,list<int>>q2(q1);
(3).元素入队 函数为:push()例如:q.push(3),意思是将3入队 ,注意队列的大小不预设
(4).元素出队 函数为:pop()例如:q.pop()
(5)。取对头元素 函数为:front()
(6),取队尾元素 函数为:back()
(7)。判断对空 函数为:empty()
(8)。队列的大小 函数为:size()返回队列的当前元素的个数9.如何实现固定大小的queue队列 在每一次元素入队列前都判断当前的队列是否满,用双向链表做queue 的底层容器可以实现例如:

1. #include<iostream>

2. #include<list>

3. #include<queue>

4. using namespace std;

5. #define QUEUE_SIZE 50 //固定大小为50

6. int main()

7. {

8. queue<int,list<int>> q;

9. if(q.size<QUEUE_SIZE)q.push(51);

10. if(q.size<QUEUE_SIZE)q.push(36);

11. if(q.size<QUEUE_SIZE)q.push(28);

12. while(!q.empty())

13. {

14. cout<<q.front()<<endl; //打印51 36 28q.pop();

15. //出队}return 0;

16. }

code:

1. #include<stdio.h>

2. #include<queue>

3. #include<string.h>

4. using namespace std;

5. int main()

6. {

7. register int i,j;

8. int m,n;

9. char c[6];

10. int x,y;

11. while(scanf("%d%d",&n,&m)!=EOF)

12. {

13. queue<int>Q[10000];

14. for(i=0;i<m;i++) {

15. scanf("%s",&c);

16. if(strcmp(c,"INIT")==0)

17. {

18. for(j=1;j<=n;j++)

19. {

20. while(!Q[j].empty())

21. Q[j].pop();

22. }

23. continue;

24. }

25. if(strcmp(c,"PUSH")==0)

26. {

27. scanf("%d%d",&x,&y);

28. Q[x].push(y);

29. continue;

30. }

31. if(strcmp(c,"POP")==0)

32. {

33. scanf("%d",&y);

34. if(Q[y].empty())

35. {

36. printf("NULLn");

37. continue;

38. }

39. else

40. printf("%dn",Q[y].front());

41. Q[y].pop();

42. }

43.

44. }

45. }

46. return 0;

47. }