- q.empty() 如果队列为空返回true,否则返回false
- q.size() 返回队列中元素的个数
- q.pop() 删除队列首元素但不返回其值
- q.front() 返回队首元素的值,但不删除该元素
- q.push() 在队尾压入新元素
- q.back() 返回队列尾元素的值,但不删除该元素
#include<cstdio>
#include<stack>//栈
#include<queue>//队列
#include<algorithm>
using namespace std;
int main()
{
stack<int >sta;
int a,b,d,c,e,f;
a=2;b=1;c=3;
sta.push(a);//进栈 a
sta.push(b);// b
sta.push(c);
d=sta.top();//出栈 c 3 逆序出栈
sta.pop();//删除栈顶元素 c 3
printf("%d\n",d);//输出栈顶元素b 1
e=sta.top();
sta.pop();//删除栈顶元素 b 1
printf("%d\n",e);
if(!sta.empty()) //判断栈中是否为空
f=sta.top();//不为空,则输出栈中下一个元素a 2
printf("%d\n",f);
return 0;
}
输出结果为3 1 2
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>//队列
using namespace std;
int main()
{
queue<int >que;
int a=5,b=4,c=3,d=2,e=1;
que.push(a);//入列
que.push(b);
que.push(c);
que.push(d);
que.push(e);
while(!que.empty())//顺序输出
{
printf("%d\n",que.front());//输出最前面的数
que.pop();//删除最前面的数
}
return 0;
}输出结果为5 4 3 2 1
优先队列
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
struct node
{
int you,ge;
bool friend operator<(node x,node y)//不能改变 只能是<
{
return x.you>y.you;
}
};
int main()
{
priority_queue<node>que;
struct node a,b,c;
a.ge=1;a.you=5;
b.ge=2;b.you=4;
c.ge=3;c.you=3;
que.push(a);//入列
que.push(b);
que.push(c);
while(!que.empty())
{
printf("%d\n",que.top().you);//按优先级输出
que.pop();
}
return 0;
}
输出结果为3 4 5