[C++ 从入门到放弃-08]C++STL之stack堆栈容器

来源:互联网 发布:热阻流软件 编辑:程序博客网 时间:2024/05/21 07:51

stack堆栈是一个后进先出的线性表,插入和删除都只能在表一端进行,插入元素的一端成为栈顶(stack top),而另一端则称为栈底(stack bottom),

  • 插入元素称为入栈(push)
  • 删除元素称为出栈(pop)

少废话,直接上干货!

stack堆栈容器头文件是 #include<stack>

stack的基本操作如下:

  • 创建stack,stack<int> s;
  • 入栈,如: s.push(x)
  • 出栈,如: s.pop()    注意:出栈操作只是删除栈顶元素,并不返回栈顶元素值。
  • 访问栈顶,如: s.top()
  • 判断栈是否为空, 如: s.empty()
  • 统计栈中的元素个数,如: s.size()
#include<iostream>#include<stack>using namespace std;int main(){stack<int> s;s.push(1);s.push(2);s.push(3);s.push(9);cout<<s.top()<<endl;cout<<s.size()<<endl;cout<<s.empty()<<endl;while(s.empty() != true){cout<<s.top()<<" ";s.pop();}cout<<endl;return 0;}


原创粉丝点击