1  #ifndef STACK_H
  2  #define STACK_H
  3
  4  #include <iostream>
  5
  6  template <class T>
  7  class stack
  8  {
 11      template <class S>
 12      friend std::ostream &operator<<( std::ostream &os, const stack<S> &s );
 13  public:
 14          stack( int size = 128 );
 15          stack( const stack &rhs );
 16          ~stack();
 17      stack<T>& operator=( const stack &rhs );
 18
 19      void  push( const T &d );
 20      const T& pop();
 21
 22      bool is_empty() const;
 23      bool is_full()  const;
 24  private:
 25      int    capacity;
 26      int    sp;
 27      T      *v;
 28
 29      void copy( const stack &other );
 30  };
 31
 32  // itt jönnek a függvény megvalósítások: nincsen .cpp fájl!
 33  template <class T>
 34  stack<T>::stack( int size )
 35  {
 36      v = new T[capacity = size];
 37      sp = 0;
 38  }
 39  template <class T>
 40  stack<T>::stack( const stack &other )
 41  {
 42      copy( other );
 43  }
 44  template <class T>
 45  stack<T>::~stack()
 46  {
 47      delete [] v;
 48  }
 49  template <class T>
 50  stack<T>& stack<T>::operator=( const stack &other )
 51  {
 52      if ( this != &other )
 53      {
 54          delete [] v;
 55          copy( other );
 56      }
 57      return *this;
 58  }
 59  template <class T>
 60  void stack<T>::copy( const stack &other )
 61  {
 62      v = new T[capacity = other.capacity];
 63      sp = other.sp;
 64
 65      // ezt a ciklust nem lehet helyettesíteni memcpy()-al!
 66      for ( int i = 0 ; i < sp; ++i )
 67          v[i] = other.v[i];  // a T típus operator=() -a
 68  }
 69
 70  // üres, vagy teli? ellenőrizze a felhasználó!
 71  template <class T>
 72  void stack<T>::push( const T &d )
 73  {
 74      v[sp++] = d;
 75  }
 76  template <class T>
 77  const T& stack<T>::pop()
 78  {
 79      return v[--sp];
 80  }
 81
 82  // ezek a függvények is template-ek, hiszen specializálhatóak
 83  template <class T>
 84  bool stack<T>::is_empty() const
 85  {
 86      return 0 == sp;
 87  }
 88  template <class T>
 89  bool stack<T>::is_full() const
 90  {
 91      return capacity == sp;
 92  }
 93
 94  // ez egy "közönséges" template függvény, stack<T> -re specializálva
 95  template <class T>
 96  std::ostream &operator<<( std::ostream &os, const stack<T> &ds )
 97  {
 98      os << "[ ";
 99      for ( int i = 0; i < ds.sp - 1; ++i )
100          os << ds.v[i] << ", ";
101      if ( ds.sp > 0 )
102          os << ds.v[ds.sp - 1];
103      os << " ]";
104      return os;
105  }
106
107  #endif /* STACK_H */
108
109