1
0
Fork 0

Ex6.3 feedback: Remove Dynamic Allocation in Stack

This commit is contained in:
Eric Teunis de Boone 2020-07-01 19:18:47 +02:00
parent 5ac86eccb3
commit 817e492ef0
2 changed files with 12 additions and 11 deletions

View file

@ -11,6 +11,7 @@ public:
Array(const Array& other) : _size(other._size) { Array(const Array& other) : _size(other._size) {
_arr = new T[other._size] ; _arr = new T[other._size] ;
_default = other._default ;
// Copy elements // Copy elements
for (int i=0 ; i<_size ; i++) { for (int i=0 ; i<_size ; i++) {

View file

@ -8,23 +8,23 @@ template<class T>
class Stack { class Stack {
// Interface // Interface
public: public:
Stack( int in_size ) { Stack( int size ):
count = 0; _s(size, 0)
_s = new Array<T>(in_size, 0); {}
}
int nitems() { return count ; } int nitems() { return count ; }
bool full() { return (count == _s->size()) ; } bool full() { return (count == _s.size()) ; }
bool empty() { return (count == 0) ; } bool empty() { return (count == 0) ; }
void push(T c) { void push(T c) {
if (full()) { if (full()) {
std::cout << "Stack::push() Error: stack is full" << std::endl ; std::cout << "Stack::push() Error: stack is full" << std::endl ;
_s->resize( _s->size() + 10 ); _s.resize( _s.size() + 10 );
} }
_s[0][count++] = c ; _s[count++] = c ;
} }
T pop() { T pop() {
@ -33,20 +33,20 @@ class Stack {
return 0 ; return 0 ;
} }
return _s[0][--count] ; return _s[--count] ;
} }
void inspect() { void inspect() {
for ( int i = nitems() - 1; i >= 0; i-- ) for ( int i = nitems() - 1; i >= 0; i-- )
{ {
std::cout << i << ": " << _s[0][i] << std::endl; std::cout << i << ": " << _s[i] << std::endl;
} }
} }
// Implementation // Implementation
private: private:
Array<T>* _s ; Array<T> _s ;
int count ; int count = 0;
}; };
#endif #endif