补充STL 中队列的使用(queue)
push(x) 将x压入队列的末端
pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值
front() 返回第一个元素(队顶元素)
back() 返回最后被压入的元素(队尾元素)
empty() 当队列为空时,返回true
size() 返回队列的长度
#include <queue>
1、普通声明
queue <int> q;
2、结构体
struct node
{
int x, y;
};
queue<node>q;
注意
-
ios::sync_with_stdio(false);//
在c++中之cin,cout 先把要输出的东西存入缓冲区,再输出,导致效率降低,
而该语句可以来打消iostream的输入和输出缓存,可节省时间,
使效率与scanf与printf相差无几,
还有应注意的是scanf与printf使用的头文件应是stdio.h而不是 iostream。 -
cin.tie(0);//
tie是将两个stream绑定的函数,空参数的话返回当前的输出流指针。
数据集超大造成 cin TLE的情况。我们可以在IO之前将stdio解除绑定,
这样做了之后要注意不要同时混用cout和printf 之类。
在默认的情况下cin绑定的是cout,每次执行 << 操作符的时候都要调用flush,这样会增加IO负担。
可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。
代码
#include <iostream>
#include <queue>
using namespace std;
int main()
{
ios::sync_with_stdio(false);//
cin.tie(0);//
queue <int> q;//声明
int m;
cin >> m;
while(m --)
{
string op;
int x;
cin >> op;
//入队
if(op =="push")
{
cin >> x;
q.push(x);
}
//出队
else if(op =="pop")
{
q.pop();
}
//输出队首元素
else if(op =="query")
{
cout << q.front() << endl;
}
//队判空
else
{
if(q.empty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
return 0;
}