STL stack应用
来源:互联网 发布:gta5捏脸数据中国美女 编辑:程序博客网 时间:2024/06/05 16:45
1. 概念
stack是一种LIFO(last-in first-out)的数据结构,其只允许在容器的尾部对数据进行操作,如下:
stack定义如下:
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from the end of the container.
stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
2. API
stack提供的API接口比较简单,如下:
(constructor) Construct stack (public member function)
empty Test whether container is empty (public member function)
size Return size (public member function)
top Access next element (public member function)
push Add element (public member function)
pop Remove element (public member function)
3. stack实现
stack是容器适配器,其通过对某种既有容器进行包装,从而提供LIFO的数据访问方法。不同的库,对stack有不同的实现,可以为deque,或者list,也可以为其他实现。
例如,SGI SQL就是通过deque实现stack,主要代码如下:
- template <class T, class Sequence = deque<T> >
- class stack {
- Sequence c; // 底层容器
- public:
- // 通过调用deque的方法完成 stack 的操作。
- bool empty() const { return c.empty(); }
- size_type size() const { return c.size(); }
- reference top() { return c.back(); }
- const_reference top() const { return c.back(); }
- void push(const value_type& x) { c.push_back(x); }
- void pop() { c.pop_back(); }
- };
4. 迭代器
stack所有元素的进出都必须符合LIFO的条件,只有stack顶端的元素,才能被访问,所以,stack不提供迭代器。
5. stack使用示例
代码如下:
输出结果: 0. size: 0 1. size: 52. size: 4
- #include <iostream>
- #include <stack>
- using namespace std;
- int main ()
- {
- stack<int> myints;
- cout << "0. size: " << (int) myints.size() << endl;
- for (int i=0; i<5; i++) myints.push(i);
- cout << "1. size: " << (int) myints.size() << endl;
- myints.pop();
- cout << "2. size: " << (int) myints.size() << endl;
- return 0;
- }
6. 结语
Stack是一个容器适配器,通过包装既有容器,从而为程序员提供了堆栈的全部功能。
参考文献:
STL源码剖析
- STL stack应用
- STL中的stack的应用
- C++ STL-stack栈的应用
- STL stack
- stl stack
- STL stack
- stl stack
- stl stack
- stL stack
- STL stack
- STL stack
- STL-stack
- STL-stack
- STL stack
- STL--stack
- STL stack
- STL STACK
- STL stack
- 二叉树的递归,非递归遍历
- locate 命令
- WARNING L16: UNCALLED SEGMENT, IGNORED FOR OVERLAY PROCESS
- find 命令概览
- jquery获得select option的值 和对select option的操作
- STL stack应用
- php1
- C#优化
- c#中的静态方法与成员
- 在Hadoop上运行SQL:程序员需知晓的13种数据工具
- JAVA中常用英文简写全拼及中文含义
- php 2
- php 3
- taobao 错误码一览表补充的