一、使用
C++队列queue模板类的定义在头文件中,queue 模板类需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque 类型。
C++队列Queue是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构。
C++队列Queue类成员函数如下:
back()返回最后一个元素
empty()如果队列空则返回真
front()返回第一个元素
pop()删除第一个元素
push()在末尾加入一个元素
size()返回队列中元素的个数
queue 的基本操作举例如下:
queue入队,如例:q.push(x); 将x 接到队列的末端。
queue出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
访问queue队首元素,如例:q.front(),即最早被压入队列的元素。
访问queue队尾元素,如例:q.back(),即最后被压入队列的元素。
判断queue队列空,如例:q.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:q.size()
二、习题&题解(共七题)
周末舞会-队列
#include <bits/stdc++.h>
using namespace std;
int n, m, t;
queue<int> s1,s2;
int main()
{
cin >> n >> m >> t;
for (int i = 1; i <= n; i++)
s1.push(i);
for (int i = 1; i <= m; i++)
s2.push(i);
for (int i = 1; i <= t; i++)
{
cout << s1.front() << " " << s2.front() << endl;
s1.push(s1.front());
s1.pop();
s2.push(s2.front());
s2.pop();
}
//system("pause");
return 0;
}
报数-队列-约瑟夫环
#include <bits/stdc++.h>
using namespace std;
int n, m, t = 1;
queue<int> s;
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
s.push(i);
while (s.size() != 1)
{
if (t == m)
{
s.pop();
t =