This is an implementation of a stack where I have used vectors. Can anyone please review it and let me know how I can improve this code and overall coding practice?
#include"iostream"
class Mystack
{
private:
int *A;
int top;
int size;
public:
Mystack(int capacity);
void push(int x);
int pop();
int topElement();
void print();
bool isEmpty();
};
Mystack::Mystack(int capacity)
{
top = -1;
size = capacity;
A = new int[capacity];
}
void Mystack::push(int x)
{
if (top + 1 == size)
{
int *vec = new int[size + size];
for (int i = 0; i < size; i++)
{
vec[i] = A[i];
}
A = vec;
size = size * 2;
top++;
A[top] = x;
return;
}
else
{
top++;
A[top] = x;
}
}
int Mystack::pop()
{
if (isEmpty())
{
std::cout << "Stack Underflow" << std::endl;
}
else
{
std::cout << "The popped element is" << A[top];
return A[top--];
}
return 0;
}
bool Mystack::isEmpty()
{
if (top == -1)
{
std::cout << "Is Empty" << std::endl;
return true;
}
else
{
std::cout << "Not Empty" << std::endl;
return false;
}
}
int Mystack::topElement()
{
std::cout << "The top element is : " << A[top];
return A[top];
}
void Mystack::print()
{
for (int i = 0; i <= top; i++)
{
std::cout << A[i] << " ";
}
}
void main()
{
Mystack s1(10);
int num, ch = 1;
while (ch >0)
{
std::cout << "\n1. PUSH" << std::endl;
std::cout << "2. TOP" << std::endl;
std::cout << "3. IsEmpty" << std::endl;
std::cout << "4. POP" << std::endl;
std::cout << "5. EXIT" << std::endl;
std::cout << "6. Print" << std::endl;
std::cout << "Enter the choice" << std::endl;
std::cin >> ch;
switch (ch)
{
case 1:
std::cout << "Enter the number to be pushed" << std::endl;
std::cin >> num;
s1.push(num);
break;
case 2:
std::cout << "Get the TOP Element" << std::endl;
s1.topElement();
break;
case 3:
std::cout << "Check Empty" << std::endl;
s1.isEmpty();
break;
case 4:
std::cout << "POP the element" << std::endl;
s1.pop();
break;
case 5: exit(0);
case 6:
s1.print();
break;
}
}
system("pause");
}