As I’m learning C++ I started implementing some common datastructures as a form of practice.
The first one being a Stack (this was the first to spring in mind).
I’ve done some programming and it’s working, but now I need some input as to what I should do otherwise. Like deleting certain stuff or other pro tips. What should I do different and why?
template <class T>
class Stack
{
private:
int* values;
int capacity;
int itemsOnStack;
public:
///////////////////
Stack()
{
Stack(32);
}
///////////////////
Stack(const int sz)
{
values = new T[sz];
capacity = sz;
itemsOnStack = 0;
}
~Stack()
{
values = 0;
// delete?
}
////////////////////
void Push(const T& item)
{
*(values + itemsOnStack) = item;
itemsOnStack++;
if(itemsOnStack > capacity)
{
capacity *= 2;
T* temp = new T[capacity];
temp = values;
values = new T[capacity];
values = temp;
}
}
///////////////////
T Pop()
{
if(itemsOnStack > 0)
{
int current = --itemsOnStack;
return *(values + current);
}
return NULL; // ? good?
}
///////////////////
T Peek()
{
if(itemsOnStack > 0)
{
int current = itemsOnStack - 1;
return *(values + current);
}
return NULL; // find something better here or shouldnt?
}
///////////////////
int Count()
{
return itemsOnStack;
}
///////////////////
int Capacity()
{
return capacity;
}
///////////////////
bool IsEmpty()
{
return itemsOnStack == 0;
}
};
Did a first pass of fixes on your code:
Things left to fix:
Copy constructor and assignment operator. At the moment, if I try to do this, it’ll break horribly:
Const correctness:
Shouldn’t I be able to call
Peek()orCount()on aconst Stack<T>?Object lifetime:
Popping an element off the stack doesn’t call the element’s destructor. Pushing an element doesn’t call the element’s constructor. Simply expanding the array calls the default constructor immediately for all new elements. The constructor should be called when the user inserts an element and not befre, and the destructor immediately when an element is removed.
And, uh, proper testing:
I haven’t compiled, run, tested or debugged this in any way. So I’ve most likely missed some bugs, and introduced a few new ones. 😉