代码改变世界

stack.h (涂鸦作)

2006-10-07 11:02  老博客哈  阅读(693)  评论(0编辑  收藏  举报

 

#pragma once

#include 
<new>
#include 
<stdexcept>


template
<typename T, int size = 100>
class stack
{
public:
    stack();
    
~stack();
    
void push(const T & element);
    T    top() 
const;
    
bool empty() const;
    
void pop();
private:
    T
* data;
    
int currentsize;
}
;

template
<typename T, int size>
inline stack
<T, size>::stack()
{
    data 
= new T[size];
    currentsize 
= -1;
    
if( data == NULL )
    
{
        
throw std::bad_alloc();
    }

}


template
<typename T, int size>
inline stack
<T, size>::~stack()
{
    delete []data;
}


template
<typename T, int size>
inline 
void stack<T, size>::push(const T &element)
{
    
if( currentsize == size - 1)
        
throw std::overflow_error( "stack push overflow" );
    
else
        data[
++currentsize] = element;
}


template
<typename T, int size>
inline 
bool stack<T, size>::empty() const
{
    
return currentsize == -1;
}


template
<typename T, int size>
inline T stack
<T, size>::top() const
{
    
if( empty() )
        
throw std::range_error("stack top range error");
    
else
        
return data[currentsize];
}


    
template
<typename T, int size>
inline 
void stack<T, size>::pop()
{
    
if( empty() )
        
throw std::range_error("stack pop range error");
    
else
        
--currentsize;
}

写着玩玩的, 当真用偶还是去用STL的!