Please have a look at the following code
template <typename T>
class Stack
{
public:
Stack(int number)
{
maxSize = number;
top = -1;
stackData = new T*(maxSize);
}
~Stack()
{
delete [] stackData;
}
int count()
{
}
bool isEmpty()
{
if(top==-1)
{
return true;
}
else
{
return false;
}
}
bool isFull()
{
if(top== (maxSize-1))
{
return true;
}
else
{
return false;
}
}
*T pop()
{
if(!isEmpty())
{
return stackData[top--]; // Remove Item From Stack
}
}
*T peek();
void push(T *pushValue)
{
if(!isFull())
{
stackData[++top] = pushValue;
}
}
private:
int maxSize;
T ** stackData;
int top;
};
In the above code, the commented line says “Removing Item from the Stack”. But actually, it is not removing, it is simply providing the value which is one value behind, right? In here, I refer removing as completely destroying that particular value from the stack.
ex: In an array which contains data 1,2,3,4 I remove ‘2’. So now it is 1,3,4
Second, what should happen inside the “peek()” method?
Third, are there are any errors that I didn’t detect?
Please help!
Conceptually, there is no difference between decrementing
topand “removing” the top item. The word “remove” is a conceptual abstraction to describe the idea that the top item in the stack is no longer an element in the stack. The fact that it is not literally removed from that location in memory is irrelevant.If you mean you want to “destroy” the top item, i.e. invoke it’s destructor and deallocate it, you need to consider the larger implications of how your
Stackclass manages memory. If the stack is supposed to take ownership of eachTobject, and eachTobject has been allocated usingnew, then you can have yourpop()functiondeletethe top item before decrementingtop. (But thenpop()can’t return a pointer to the deleted element.) If the stack doesn’t take ownership of each item, then it is up to the caller ofpop()to manage the lifetime/deallocation of the element.Next, the
peek()method simply returns a pointer to the top item, without removing it from the stack.And finally, you are not correctly allocating the array of
T*pointers. The syntax should be:The code you posted uses parentheses after
newinstead of brackets, which is not what you want here.