I started reading up on data structures from scratch after some unconsolidated knowledge gathered from the web.
(If anyone is interested, the book I'm following is "Data Structure and program design in C++" --by Robert L. Kruse && Alexander J. Ryba)
Without further ado, here is my implementation of a stack..in a contiguous array.
(I know the exception handling can be done in a less lazy way.... would do that if I ever use this code in any program)
Code:
namespace mm
{
enum stack_error{overflow,underflow,beheaded};
template <typename T, int Size>
class stack
{
private:
T mem[Size];
int stack_ptr; // The offset from mem to get the pointer to the head
public:
stack():stack_ptr(-1){};
void push(const T& in)
{
if(++stack_ptr >= Size) throw(overflow);
else mem[stack_ptr] = in;
}
T& head()
{
if(stack_ptr == -1) throw(beheaded);
return mem[stack_ptr];
}
void pop()
{
if(--stack_ptr < -1 ) throw(underflow);
}
bool empty(){return stack_ptr==-1?true:false;};
int size(){return stack_ptr+1;};
};
}
It worked nicely for all test cases I came up with.
Still.. to make sure...:
Am I doing something that is considered 'bad' in the norm ?