前言
迄今为止,我们已经分析了vector
、list
、deque
容器,而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
,它也是一种配接器,而不是容器。