STL学习记录(十五):Stack
2015-07-31 22:33
323 查看
STL中的特殊容器Stack
准确来说Stack是容器适配器类型,与我们数据结构中所学的概念一样这种容器的特性就是Last Input First Output。该容器通过push、pop方法对栈头的元素进行操作。主要的成员函数如下:
成员函数 | 说明 |
---|---|
empty( ) | 判断栈是否为空 |
size( ) | 返回栈的大小 |
push( val ) | 将元素加入到栈首 |
pop( ) | 取出栈中的首元素 |
top( ) | 访问栈首元素 |
emplace( val ) | 将元素加入到栈首,元素在作为参数传递的时候通过自身构造函数构造 |
swap( stc ) | 将stc栈进行元素交换 |
// stack::swap stack::size #include <iostream> #include <stack> using namespace std; int main () { stack<int> foo,bar; foo.push (10); foo.push(20); foo.push(30); bar.push (111); bar.push(222); foo.swap(bar); cout << "size of foo: " << foo.size() << endl; cout << "size of bar: " << bar.size() << endl; return 0; }
// stack::push/pop #include <iostream> #include <stack> using namespace std; int main () { stack<int> mystack; for (int i=0; i<5; ++i) mystack.push(i); cout << "Popping out elements..."; while (!mystack.empty()) { cout << ' ' << mystack.top(); mystack.pop(); } cout << endl; return 0; }
// stack::emplace #include <iostream> #include <stack> #include <string> using namespace std; int main () { stack<string> mystack; mystack.emplace ("First sentence"); mystack.emplace ("Second sentence"); cout << "mystack contains:\n"; while (!mystack.empty()) { cout << mystack.top() << endl; mystack.pop(); } return 0; }
相关文章推荐
- 如何设计系统的错误码及错误信息
- 我跟敏捷开发的故事--背景
- Spring MVC 中的基于注解的 Controller
- <Java>short与byte在有符号大数据时的转换
- 【IDF实验室】图片里的英语
- CATranstion动画
- php5.4n 长链接 bug
- Android大图片裁剪终极解决方案(上:原理分析)
- Android固定标题栏/底栏方法
- RCFile 结构解析
- MapConrol各基本功能的实现代码
- 狸猫浏览器v2.0功能解析
- python函数中各类参数的讨论
- 实模式与保护模式
- SQL到NoSql
- ( ̄y▽ ̄)~ 智能手机II
- 数据库系统0T1(0):基础概念
- Leetcode #77 Combinations
- 做个mp3播放器mciSendString
- hihocoder 1122最大二分匹配匈牙利算法