Stack:栈
概念:一种先进后出的容器
头文件为:#include<stack>
定义:</stack>
stack <int> st; stack <string> ss;
成员函数与操作方法
empty()// 堆栈为空则返回真 pop() //移除栈顶元素 push() //在栈顶增加元素 size() //返回栈中元素数目 top() //返回栈顶元素
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<int>st;
int m;
int temp;
cin>>m;
for(int i=0;i<m;i++)
{
cin>>temp;
st.push(temp);
cout<<st.size()<<" "<<st.top()<<endl;
}
st.pop();
cout<<st.top()<<endl;
if(st.empty()!=true)
{
cout<<"yes"<<endl;
}
return 0;
}结果如图所示:
queue:队列
概念:具有先进先出特征的容器
头文件:#include<queue>
定义:</queue>
queue<int>q; queue<string>q1;
成员函数与操作方法
q.push(x); // 入队列 q.pop(); // 出队列 q.front(); // 访问队首元素 q.back(); // 访问队尾元素 q.empty(); // 判断队列是否为空 q.size(); // 访问队列中的元素个数
代码示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
queue<int> q;
int m;
int temp;
cin>>m;
for(int i=0;i<m;i++)
{
cin>>temp;
q.push(temp);
cout<<q.size()<<" "<<q.back()<<endl;
}
q.pop();
cout<<q.front()<<endl;
if(q.empty()!=true)
{
cout<<"yes"<<endl;
}
return 0;
}结果如图所示:
参考引用:stack/queue

京公网安备 11010502036488号