#include <iostream>
#include <deque>
using namespace std;
template <typename T, typename Sequence = deque<T>>
class stack // stack内部使用默认容器deque
{
friend bool operator== <T> (const stack &x, const stack &y);
friend bool operator< <T> (const stack &x, const stack &y);
public:
typedef typename Sequence::size_type size_type; // 一种类型 足以保存当前类型的最大对象的大小
typedef typename Sequence::value_type value_value; // 元素类型
typedef typename Sequence::reference reference; // 元素的引用
typedef typename Sequence::const_reference const_reference; // 元素的常量引用
protected:
Sequence c; // 实际维护的容器
public:
stack() : c(){} // 默认构造函数 构造一个空栈
stack(const Sequence &s) : c(s){} // 接受一个容器的构造函数
// 下面的操作完全使用内部容器的成员函数实现
bool empty() const // 若a包含任何元素但会false 否则返回true
{
return c.empty();
}
size_type size() const // 返回a中元素的数目
{
return c.size();
}
reference top() // 返回栈顶元素 但不将元素出栈
{
return c.back();
}
const_reference top() const // 重载版本
{
return c.back();
}
void push(const value_value &x) // 压栈
{
c.push_back(x);
}
void pop() // 出栈
{
c.pop_back();
}
};
template <typename T, typename Sequence>
bool operator==(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return x.c == y.c;
}
template <typename T, typename Sequence>
bool operator<(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return x.c < y.c;
}
template <typename T, typename Sequence>
bool operator!=(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return !(x == y);
}
template <typename T, typename Sequence>
bool operator>(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return x < y;
}
template <typename T, typename Sequence>
bool operator<=(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return !(y < x);
}
template <typename T, typename Sequence>
bool operator>=(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return !(y < x)
}
int main()
{
stack<int> intstack;
for (size_t ix = 0; ix != 10; ++ix)
{
intstack.push(ix);
}
while (!intstack.empty())
{
int value = intstack.top();
intstack.pop();
cout << value << " ";
}
}
stack(仿sgi stl)
最新推荐文章于 2022-10-09 21:21:19 发布