<方法1>
namespace my_stack
{
template<class T, class Cont>
class stack
{
public:
stack(){}
~stack(){}
public:
void push(const T &x)
{
v.push_back(x);
}
void pop()
{
v.pop_back();
}
T& top()
{
return v.back();
}
bool empty()const
{
return v.empty();
}
size_t size()
{
return v.size();
}
private:
Cont v;
};
}
<方法2>
namespace my_stack
{
template<class T>
class stack
{
public:
stack(int sz = STACK_DEFAULT_SIZE)
{
_capacity = sz > STACK_DEFAULT_SIZE ? sz : STACK_DEFAULT_SIZE;
_base = new T[_capacity];
_top = 0;
}
~stack()
{
if (_base)
{
delete[] _base;
_capacity = _top = 0;
}
}
public:
void push(const T &x)
{
if (_top >= _capacity)
return;
_base[_top++] = x;
}
void pop()
{
if (_top == 0)
return;
_top--;
}
T& top()
{
if (_top == 0)
return 0;
return _base[_top - 1];
}
bool empty()const
{
return _top == 0;
}
private:
enum{STACK_DEFAULT_SIZE = 8};
T* _base;
size_t _capacity;
size_t _top;
};
}