SGISTL源码探究-stack配接器

前言

迄今为止,我们已经分析了vectorlistdeque容器,而stack并不是一个容器,它是依据一种容器作为底层结构,然后根据自己的要求改变容器提供的接口。而在SGISTL的实现中,stack默认是以deque为底部结构,并且封装了一些接口并且stack中没有迭代器,它也并不需要,因为栈这种结构,并不支持遍历等操作,而出栈入栈这些操作,直接使用deque提供的操作,然后自己封装一下就行了。
由于它的源码比较简单,我们直接贴出代码进行分析就行了。

stack源码

stack定义部分
template <class T, class Sequence = deque<T> >
#else
template <class T, class Sequence>
#endif
class stack {
  //重载操作符==和<
  friend bool operator== __STL_NULL_TMPL_ARGS (const stack&, const stack&);
  friend bool operator< __STL_NULL_TMPL_ARGS (const stack&, const stack&);
public:
  //声明一些常用的数据类型
  typedef typename Sequence::value_type value_type;
  typedef typename Sequence::size_type size_type;
  typedef typename Sequence::reference reference;
  typedef typename Sequence::const_reference const_reference;
protected:
  //底层的容器,即deque
  Sequence c;
stack提供的接口
public:
  //使用deque提供的empty
  bool empty() const { return c.empty(); }
  //使用deque提供的size
  size_type size() const { return c.size(); }
  //访问栈顶元素,即deque的最后一个元素
  reference top() { return c.back(); }
  const_reference top() const { return c.back(); }
  //压入栈,使用push_back即可
  void push(const value_type& x) { c.push_back(x); }
  //弹出栈,使用pop_back
  void pop() { c.pop_back(); }
};
重载操作符
//判断两者元素是否相等即可
template <class T, class Sequence>
bool operator==(const stack<T, Sequence>& x, const stack<T, Sequence>& y) {
  return x.c == y.c;
}

template <class T, class Sequence>
bool operator<(const stack<T, Sequence>& x, const stack<T, Sequence>& y) {
  return x.c < y.c;
}
例子
#include <iostream>
#include <stack>
//#include <list>
//#include <vector>
using namespace std;
int main()
{
  stack<int> st;
  /* 可以指定采取其他容器作为底层结构,如
   * stack<int, list<int> > st;
   * stack<int, vector<int> > st;
   */
  st.push(1);
  st.push(2);
  st.push(3);

  cout << "size " << st.size() << endl;
  cout << "top " << st.top() << endl;

  st.pop();

  cout << "size " << st.size() << endl;
  cout << "top " << st.top() << endl;

  st.pop();

  cout << "size " << st.size() << endl;
  cout << "top " << st.top() << endl;

  st.pop();
  if(st.empty())
    cout << "empty stack" << endl;
  return 0;
}
### __小结__

本小节介绍了stack是如何实现的,如果之前没有了解过stack源码,肯定会对它的实现感到惊讶。因为它仅仅就只是利用了容器的实现,然后自己封装一些接口就完事了,它并不是容器,而是一种配接器,即修改某物的接口,供自己使用。
下一小节中,我们将介绍queue,它也是一种配接器,而不是容器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值