I am trying to implement some of the methods of the class "stack". For the push() method I am trying to duplicate the capacity of the array if the top of the stack equals the capacity. The top is the item of the next slot. I was doing this by creating a new array with double the capacity of the original array and then copying the content over. All the other methods I implemented (empty(), pop(), top()) seem to be working fine but the push function prints random values for the first 4 items of the stack for some reason if the stack has more than 10 elements (The capacity had to be increased). Why is this problem happening?
#include <iostream>
using namespace std;
class stack
{
public:
stack();
bool empty();
void pop();
void push(int x);
int &topElem();
private:
int *buffer;
int top; // Top element of stack
int capacity = 10; // Capacity of array
};
stack::stack()
{
int *val = new int[capacity];
buffer = val;
top = 0;
}
bool stack::empty()
{
if(top == 0)
return true;
else
return false;
}
void stack::push(int x)
{
if(top == capacity)
{
int *newArray = new int[capacity * 2];
for(int i = 0; i < capacity; i++)
{
newArray[i] = buffer[i];
//cout << "newArray[" << i << "]: " << newArray[i] << endl;
}
buffer = newArray;
delete[] newArray;
newArray = NULL;
}
buffer[top] = x;
top++;
}
void stack::pop()
{
if(!empty())
{
top--;
}
else
cout << "Stack is empty!" << endl;
}
int& stack::topElem()
{
return buffer[top - 1];
}
int main()
{
stack plates;
for (int i = 0; i < 20; i++) // Add 20 elements to the stack
{
plates.push(i);
}
while (!plates.empty())
{
cout << plates.topElem() << endl; // Prints the elemtents of the stack
plates.pop(); // Pops the last element of the stack
}
return 0;
}
// Output 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 393 -1250224288 393 -1250206816