您的位置:首页 > 编程语言 > C语言/C++

STL之stack

2014-02-18 16:40 190 查看
        stack(栈)在计算机科学中是限定仅在表尾进行插入或删除操作的线性表。栈是一种数据结构,它按照后进先出(First In Last Out, FILO)的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据。栈只有一个出口,允许插入元素(只能在栈顶上插入)、删除元素(只能删除栈顶元素)、取得栈顶元素等操作。用桶堆积物品,先堆进来的压在底下,随后一件一件往堆。取走时,只能从上面一件一件取。堆和取都在顶部进行,底部一般是不动的。栈就是一种类似桶堆积物品的数据结构,进行删除和插入的一端称栈顶,另一堆称栈底。插入一般称为进栈,删除则称为退栈。栈也称为后进先出表。

        在STL中,栈是以别的容器作为底部结构(如果不指定容器,默认是用deque来作为其底层数据结构的),再将接口改变,使之符合栈的特性。

在STL中栈一共就5个常用操作函数:

push() 在栈顶插入元素

pop()  删除栈顶元素(不会返回栈顶元素的值)

top()  返回栈顶元素

size()  返回栈中元素的数目

empty() 堆栈为空则返回真

 

stack 模板类的定义在<stack>头文件中。

stack 模板类需要两个模板参数,一个是元素类型,一个容器类型,但只有元素类型是必要的,在不指定容器类型时,默认的容器类型为deque。

定义stack 对象的示例代码如下:

stack<int> s1;

stack<int,vector<int>> s2;

stack 的基本操作有:

入栈,如例:s.push(x);

出栈,如例:s.pop();注意,出栈操作只是删除栈顶元素,并不返回该元素。

访问栈顶,如例:s.top()

判断栈空,如例:s.empty(),当栈空时,返回true。

访问栈中的元素个数,如例:s.size()。

VS2008中栈的源代码

template<class _Ty, class _Container = deque<_Ty> >
class stack
{   // LIFO queue implemented with a container
public:
typedef _Container container_type;
typedef typename _Container::value_type value_type;
typedef typename _Container::size_type size_type;
typedef typename _Container::reference reference;
typedef typename _Container::const_reference const_reference;

stack() : c()
{   // construct with empty container
}

explicit stack(const _Container& _Cont) : c(_Cont)
{   // construct by copying specified container
}

bool empty() const
{   // test if stack is empty
return (c.empty());
}

size_type size() const
{   // test length of stack
return (c.size());
}

reference top()
{   // return last element of mutable stack
return (c.back());
}

const_reference top() const
{   // return last element of nonmutable stack
return (c.back());
}

void push(const value_type& _Val)
{   // insert element at end
c.push_back(_Val);
}

void pop()
{   // erase last element
c.pop_back();
}

const _Container& _Get_container() const
{   // get reference to container
return (c);
}

protected:
_Container c;   // the underlying container
};


栈的使用范例:

#include <stack>
#include <vector>
#include <list>
#include <cstdio>
using namespace std;
int main()
{
//可以使用list或vector作为栈的容器,默认是使用deque的。
stack<int, list<int>>    a;
stack<int, vector<int>>   b;
int i;

//压入数据
for (i = 0; i < 10; i++)
{
a.push(i);
b.push(i);
}

//栈的大小
printf("%d %d\n", a.size(), b.size());

//取栈项数据并将数据弹出栈
while (!a.empty())
{
printf("%d ", a.top());
a.pop();
}
putchar('\n');

while (!b.empty())
{
printf("%d ", b.top());
b.pop();
}
putchar('\n');
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ STL stack