C++/summary

클래스 템플릿을 이용하 스택 메모리를 구현해보자.

gandus 2010. 10. 11. 10:43

#include<iostream>

using namespace std;

 

class FullStack{};

 

class EmptyStack{};

 

 

template <class T>

class Stack {

 

private:

      T *s;

      int size, top;

     

public:

      Stack (int n = 100 ) : size(n), top(-1){

            s= new T[size];

      }

 

      ~Stack() { delete []s; }

 

      void push(T v);

 

      T pop();

 

      bool isEmpty() const { return top == -1; }

      bool isFull() const { return top == size -1; }

 

};

 

 

template <typename T>

void Stack<T> ::push(T v) {

     

      if( isFull()  )

            throw FullStack();

      s[ ++top] = v;

}

 

template <typename T>

T Stack<T> ::pop(){

     

      if( isEmpty() ){

            throw EmptyStack();

      }

      return s[ top--] ;

 

}

 

 

void main(){

     

      Stack<int> s;

 

      s.push(100);

      s.push(200);

      s.push(300);

      s.push(400);

 

      for(int i=0; i<4; i++){

            cout<< s.pop()<< endl;

      }

 

     

      Stack<char> s1;

 

      s1.push("l");

      s1.push("l");

      s1.push("u");

      s1.push("f");

 

      for(int i=0; i<4; i++){

            cout<< s.pop();

      } 

}