[关闭]
@rg070836rg 2015-08-16T15:05:57.000000Z 字数 1472 阅读 1624

STL栈实现及书本对比

data_structure

返回目录


是一种只允许在一端进行插入与移除的数据结构。


一、课本分析

书本上的栈,主要分为两种实现

  • 顺序栈
  • 链栈

顺序栈需要事先指定元素,空间固定。
链栈随用随申请,一般不会出现空间问题。

栈实现比较简便,功能明确,

具体实现可以参见:顺序栈以及双栈的设计与测试


二、STL栈

文章内容参考:STL系列之二 stack栈

下面,贴出在VS中,stack的定义

  1. template<class _Ty, class _Container = deque<_Ty> >
  2. class stack
  3. { // LIFO queue implemented with a container
  4. public:
  5. typedef _Container container_type;
  6. typedef typename _Container::value_type value_type;
  7. typedef typename _Container::size_type size_type;
  8. typedef typename _Container::reference reference;
  9. typedef typename _Container::const_reference const_reference;
  10. stack() : c()
  11. { // construct with empty container
  12. }
  13. explicit stack(const _Container& _Cont) : c(_Cont)
  14. { // construct by copying specified container
  15. }
  16. bool empty() const
  17. { // test if stack is empty
  18. return (c.empty());
  19. }
  20. size_type size() const
  21. { // test length of stack
  22. return (c.size());
  23. }
  24. reference top()
  25. { // return last element of mutable stack
  26. return (c.back());
  27. }
  28. const_reference top() const
  29. { // return last element of nonmutable stack
  30. return (c.back());
  31. }
  32. void push(const value_type& _Val)
  33. { // insert element at end
  34. c.push_back(_Val);
  35. }
  36. void pop()
  37. { // erase last element
  38. c.pop_back();
  39. }
  40. const _Container& _Get_container() const
  41. { // get reference to container
  42. return (c);
  43. }
  44. protected:
  45. _Container c; // the underlying container
  46. };

不难发现,栈并没有提供自身的函数,而是封装了其他的数据结构,提供了对外的接口函数。

在c++面向对象实用教程一书中,第275页,讲述了stack和queue本身都不是独立的容器,默认条件下,是用的deque的容器来构造的。


在C++ Primer中第九章详细介绍了容器类型,deque双向队列是一种双向开口的连续线性空间,可以高效的在头尾两端插入和删除元素。


相比之下,STL栈并没有实现判满操作,因为,其使用容器类,不存在空间分配问题。同时,由于其余功能均采用容器,提供接口访问。在头部插入和删除的效率很高。使用时,仅需要包含其头文件即可。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注