stack堆栈容器
2015-08-19 19:20
162 查看
堆栈是一种线性表,插入和删除操作只在表的一端进行,该端成为栈顶,另一端则称为栈底。元素的入栈和出栈都是在栈顶进行的,因此堆栈是一种后进先出表(LIFO)。C++ STL的堆栈泛化是通过现有的序列容器来实现的,默认使用的是双端队列deque的数据结构。在STL中,stack的元素出栈操作是不返回栈顶元素的,获得栈顶元素需要调用相应的取栈顶函数才能获得,这种分离的实现,是考虑到出栈函数若是直接返回栈顶元素,将会导致返回值的数据引用安全问题或者不必要的低效复制函数的调用。
(1) stack()
stack<int> s;
(2) stack(const stack&)
复制构造函数。
stack<int,list<int>> s1;
stack<int,list<int>> s2(s1);
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
stack<int> s;
while(!s.empty())
{
s.pop();
}
cout<<s.top()<<endl;
s.pop();
栈顶判断是否为空利用函数empty。
创建stack对象
主要有以下两种方式。(1) stack()
stack<int> s;
(2) stack(const stack&)
复制构造函数。
stack<int,list<int>> s1;
stack<int,list<int>> s2(s1);
元素入栈
入栈函数为push函数,C++的STL是不预设堆栈的大小的,入栈函数不考虑堆栈空间是否为满,均将元素压入堆栈。stack<int> s;
s.push(1);
s.push(2);
s.push(3);
元素出栈
出栈函数为pop函数,该函数并没有判断堆栈是否为空,需要自行判断堆栈是否为空,才可以执行pop函数。stack<int> s;
while(!s.empty())
{
s.pop();
}
取栈顶元素
堆栈stack容器的栈顶元素的读取函数为top函数,取栈顶元素也要判断堆栈是否为空,取出的栈顶元素才有意义。cout<<s.top()<<endl;
s.pop();
栈顶判断是否为空利用函数empty。
#include<iostream> #include<stack> using namespace std; int main() { stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); while(!s.empty()) { cout<<s.top()<<endl;//5、4、3、2、1 s.pop(); } return 0; }
堆栈的大小
堆栈元素的个数可以用size函数来获得。#include<iostream> #include<stack> #include<list> #define STACK_SIZE 100 using namespace std; int main() { stack<int,list<int> > s; if(s.size()<STACK_SIZE) { s.push(68); } if(s.size()<STACK_SIZE) { s.push(50); } if(s.size()<STACK_SIZE) { s.push(10); } while(!s.empty()) { cout<<s.top()<<endl;//10/50/68 s.pop(); } return 0; }
相关文章推荐
- SDL显示图像和文字
- mini2440串口模块总结
- Android Studio下Intent隐式启动,发短信,拨号,打电话,访问网页
- 【Java】-基础-线程
- 题目:岛屿的个数
- 按键原理和软硬件按键消抖动
- PAT-PAT (Advanced Level) Practise 1008. Elevator (20) (简单模拟)【一星级】
- 1094. The Largest Generation
- 8.19 多线程的几种实现方式
- POJ 3279 Dungeon Master
- 在navgationController中添加UISegmentedControl
- wowza简介
- ObjectiveC开发教程--字符串的基本操作处理方法
- 题目:尾部的零
- ItailorCode
- ajax(三) ajax提交表单、ajax实现文件上传
- 什么是进程
- 第十章 面向对象编程:继承和多态
- 题目:将整数A转换为B
- oracle游标:查询并打印员工的姓名和薪水