I have implemented a dynamic array based stack. Can someone point out any pitfalls or things that can be done better?
MyStack.h
#ifndef MYSTACK_H
#define MYSTACK_H
#include <iostream>
#include <stdexcept>
template<class T>
class MyStack
{
private:
T* m_array;
int m_count;
int m_max_size;
static const int m_growth_factor = 2;
static const int m_initial_max_size = 10;
public:
MyStack();
inline MyStack(const MyStack<T> &rhs) { *this = rhs; }
void operator=(const MyStack<T> &rhs);
MyStack(int initial_max_size);
~MyStack();
void push(T data);
void pop();
void clear();
inline bool empty() { return m_count == 0; }
inline T& top() { return m_array[m_count - 1]; }
inline int size() { return m_count; }
private:
void init();
void increase_array_size();
};
template <class T>
MyStack<T>::MyStack() : m_count(0), m_max_size(m_initial_max_size)
{
init();
}
template <class T>
MyStack<T>::MyStack(int initial_max_size) : m_count(0), m_max_size(initial_max_size)
{
init();
}
template <class T>
MyStack<T>::~MyStack()
{
delete [] m_array;
}
template <class T>
void MyStack<T>::init()
{
m_array = new T[m_max_size];
m_count = 0;
}
template <class T>
void MyStack<T>::increase_array_size()
{
m_max_size = m_growth_factor * m_max_size;
T* tmp = new T[m_max_size];
for(int i = 0; i < m_count; i++)
tmp[i] = m_array[i];
delete [] m_array;
m_array = tmp;
}
template <class T>
void MyStack<T>::push(T data)
{
if(m_count == m_max_size)
increase_array_size();
m_array[m_count++] = data;
}
template <class T>
void MyStack<T>::pop()
{
if(m_count == 0)
throw std::underflow_error("Underflow Exception!!!");
m_count--;
}
template <class T>
void MyStack<T>::clear()
{
delete [] m_array;
m_max_size = m_initial_max_size;
init();
}
template <class T>
void MyStack<T>::operator=(const MyStack<T> &rhs)
{
if(this != &rhs)
{
delete [] m_array;
init();
for(int i = 0; i < rhs.m_count;i++)
{
this->push(rhs.m_array[i]);
}
}
}
#endif // MYSTACK_H
main.cpp
#include <iostream>
#include "MyStack.h"
using namespace std;
int main(int argc, char* argv[])
{
MyStack<int> stack;
int sum = 0;
for(int i = 0; i < 15; i++)
stack.push(i);
while(!(stack.empty()))
{
sum += stack.top();
stack.pop();
}
cout << "sum: " << sum << endl;
stack.push(10);
stack.push(20);
stack.top() -= 5;
cout << "stack.top() is now " << stack.top() << endl;
MyStack<char> stack2;
stack2.push('t');
stack2.push('s');
stack2.push('e');
stack2.push('T');
while(!(stack2.empty()))
{
cout << stack2.top();
stack2.pop();
}
cout << endl;
stack2.push('A');
stack2.push('B');
stack2.push('C');
stack2.clear();
stack2.push('D');
stack2.push('E');
stack2.push('F');
while(!(stack2.empty()))
{
cout << stack2.top();
stack2.pop();
}
cout << endl;
}
Output:
sum: 105 stack.top() is now 15 Test FED