std::stack使用总结

版权声明:假装这里有个版权声明…… https://blog.csdn.net/CV_Jason/article/details/86002463

Stack(堆栈)

  stack是一种简单而常用的数据结构,stl库中提供了现成的实现方案。
在这里插入图片描述
  在使用stack的时候,需要包含头文件stack,其在std中的定义如下:

template<
    class T,
    class Container = std::deque<T>
> class stack;

  第一个参数定义了元素的类型,第二个参数表示stack内部实际存放元素的容器,默认使用的是stl::deque。之所以选择deque而非vector,是因为deque移除元素时会释放内存,且不必在重分配(rellocation)时复制全部的元素
  显然,stl提供的stack并不是一个独立的容器,而是基于deque的二次开发。Class Stack中的实现也是很单纯的把stack各项操作转化为deque成员函数的调用——

在这里插入图片描述
  显然,改接口的定义符合stl容器的通用标准,除了deque之外,还可以指定底层容器为stl::vector何std::list,根据使用场景不同,不同容器各有优势。

核心接口

Stack的核心接口由3个成员函数提供:push、pop和top:

  • push 将一个元素放人stack内;
  • pop 从stack移除一个元素;
  • top 返回stack栈顶元素

需要注意的是,对空堆栈进行pop和top操作,会导致不明确的结果,具体因编译器而异。比如,在Visual Studio 2017上对一个只有10个元素的stack执行11次出栈操作,VS会报异常,而gcc4.9则不会。
在这里插入图片描述

Class stack<>

成员函数

序号 函数名 功能
1 T top() 访问栈顶元素
2 bool empty() 检测底层容器是否为空
3 int size() 返回容器的元素个数
4 void push(T) 向栈顶插入元素
5 void emplace() C++11新标准,于顶原位构造元素,或者可以理解为在栈顶位置替换元素
6 void pop() 删除栈顶元素
7 void swap(stack&s) 交换内容,这里是两个堆栈的整体交换

  此外,stack还封装了==,!=,<=,>=<,>运算符操作,同理,也是基于底层容器的封装。例如,gcc4.9的实现如下:

template<typename _Tp, typename _Seq>
    inline bool
    operator<(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
    { return __x.c < __y.c; }

  /// Based on operator==
  template<typename _Tp, typename _Seq>
    inline bool
    operator!=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
    { return !(__x == __y); }

  /// Based on operator<
  template<typename _Tp, typename _Seq>
    inline bool
    operator>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
    { return __y < __x; }

  /// Based on operator<
  template<typename _Tp, typename _Seq>
    inline bool
    operator<=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
    { return !(__y < __x); }

  /// Based on operator<
  template<typename _Tp, typename _Seq>
    inline bool
    operator>=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
    { return !(__x < __y); }

  实际上,关于stack的实现,stl还做了很多工作,如果你去看vs或者gcc关于stack的实现的话,会有300多行代码,但是大多是关于平台兼容性和健壮性的操作,一般情况下用不到。

猜你喜欢

转载自blog.csdn.net/CV_Jason/article/details/86002463
今日推荐