栈的简单实现——使用C++容器库(STL Stack)
2016-02-06 12:28
316 查看
前言
作为比较简单的数据结构,使用C++容器库中的栈(std::stack)也相对比较简单。在头文件中,栈的定义为:
template< class T, class Container = std::deque<T> > class stack;
Stack
常用函数:
top():访问栈顶empty():判断栈空
size():返回栈中元素数
push():向栈顶插入元素
pop():删除栈顶元素
代码
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <stack> using namespace std; int main() { int n; while (cin>>n) { stack<int> s; string ch; int val; while (n--) { cin>>ch; if (ch == "PUSH") { cin>>val; s.push(val); } else if (ch == "POP") { if (!s.empty()) s.pop(); } else if (ch == "TOP") { if (!s.empty()) cout<<"Top : "<<s.top()<<endl; else cout<<"Empty"<<endl; } cout<<"Size : "<<s.size()<<endl; } cout<<endl; } }
测试结果
参考资料
http://zh.cppreference.com/w/cpp/container/stack相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 如何组织构建多文件 C 语言程序(二)
- 关于指针的一些事情
- 如何写好 C main 函数
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#数据结构之顺序表(SeqList)实例详解
- Lua中调用C++函数示例
- Lua和C语言的交互详解
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(七):数据结构详解
- Lua教程(二):C++和Lua相互传递数据示例
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构之队列(Quene)实例详解
- C#数据结构揭秘一
- C#数据结构之单链表(LinkList)实例详解
- C++联合体转换成C#结构的实现方法
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解