Customized version of Stack C++(自定义版本)

2014-11-24 07:10:49 · 作者: · 浏览: 0
[cpp]
#ifndef stack_
#define stack_
#include "stdafx.h"
//#include
//using namespace std;
//exception
class OutOfBounds{
public:
OutOfBounds(){}
};
//change array's size
template
void Changesize1D(T * &arr,const int& size,const int& ToSize){
T* tmp = new T[size];
tmp = arr;
arr = new T[ToSize];
for(int i=0; i< size; ++i){
arr[i] = tmp[i];
}
delete[] tmp;
}
template
class Stack{
//friend ostream& operator<<(ostream&, const Stack&);
public:
Stack();
~Stack(){delete []stack;};
T Top() const;
void Pop();
void Push(const T& x);
int Size() const;
bool Empty();
private:
int top;
int Maxtop;
T* stack;
};
template
Stack::Stack() {
stack = new T[1];
top = -1;
Maxtop = 0;
}
template
T Stack::Top() const{
if(top == -1){
throw OutOfBounds();
}else{
return stack[top];
}
}
template
void Stack::Pop(){
--top;
//change array capacity when the list size drops to
//one-fourth of the array capacity
if((top + 1 <= (Maxtop + 1)/4) && Maxtop >0){
Maxtop = (Maxtop - 1)/2;
Changesize1D(stack,top + 1, Maxtop + 1);
}
}
template
void Stack::Push(const T& x){
//if there is not enough space to accommodate the new element,
//double the array capacity
if(top == Maxtop){
Maxtop = Maxtop * 2 + 1;
Changesize1D(stack,top + 1,Maxtop + 1);
}
stack[++top] = x;
}
template
int Stack::Size() const{
return top + 1;
};
template
bool Stack::Empty(){
return top == -1;
}
/*
template
ostream& operator<<(ostream& out, const Stack& s){
out << "The stack has " << s.Size() << " element(s)" << endl;
return out;
}*/
#endif
Test it
[cpp]
// Stack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Stack1.h"
#include
using namespace std;
int main(int argc, char* argv[])
{
Stack t;
try
{
t.Top();
}
catch (OutOfBounds e)
{
cout << "no element" << endl;
}
t.Push(1);
cout << "after push 1, the top:" << t.Top() << endl;
cout << "after push 1, is empty :" <
t.Pop();
cout << "after pop, is empty " <
for(int i=0; i<10; ++i){
t.Push(i);
}
while(!t.Empty()){
cout << t.Top() << endl;
t.Pop();
}
return 0;
}