I implemented a Stack in C++ using a dynamic C-style array. I tried sticking to the most important functions a Stack has to have to be usable. This is meant to only be for integers. I appreciate any suggestions on how to improve this. Here is my code:
Stack.h
#ifndef STACK_H
#define STACK_H
#include <cstdint>
#include <algorithm>
class Stack
{
public:
Stack(int32_t u_size = 10) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ u_size }{ // constructor
m_stack_arr = new int32_t[u_size];
};
~Stack() { // destructor
delete[] m_stack_arr;
};
Stack(const Stack& other) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ 0 }{ // copy constructor
for (int32_t i = 0; i < other.size(); i++)
{
push(other.m_stack_arr[i]);
}
}
Stack(Stack&& other) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ 0 }{ // move constructor
m_stack_arr = std::exchange(other.m_stack_arr, nullptr);
}
Stack& operator=(const Stack& other) { // copy assignment operator
if (this != &other)
{
clear();
for (int32_t i = 0; i < other.size(); i++)
{
push(other.m_stack_arr[i]);
}
}
return *this;
}
Stack& operator=(Stack&& other) { // move assignment operator
if (this != &other)
{
m_stack_arr = std::exchange(other.m_stack_arr, nullptr);
m_size = other.m_size;
m_capacity = other.m_capacity;
m_current_ind = other.m_current_ind;
}
return *this;
}
void clear(int32_t new_capacity = 10); // clear stack and initialise new empty array
bool is_empty() const; // check if stack is empty
int32_t pop(); // delete value on top and return it
int32_t peek() const; // return value on top of the stack
void push(int32_t u_value); // add value to stack
int32_t size() const; // return size
private:
void extend(); // double capacity
int32_t m_current_ind;
int32_t m_size;
int32_t m_capacity;
int32_t* m_stack_arr;
};
#endif
Stack.cpp
#include "Stack.h"
#include <stdexcept>
void Stack::clear(int32_t new_capacity)
{
delete[] m_stack_arr;
m_stack_arr = new int32_t[new_capacity];
m_capacity = new_capacity;
m_current_ind = -1;
m_size = 0;
}
bool Stack::is_empty() const
{
return !m_size;
}
int32_t Stack::pop()
{
if (!is_empty())
{
m_size--;
return m_stack_arr[m_current_ind--];
}
throw std::out_of_range("Stack is already empty.");
}
int32_t Stack::peek() const
{
if (!is_empty())
{
return m_stack_arr[m_current_ind];
}
throw std::out_of_range("Stack is empty.");
}
void Stack::push(int32_t u_value)
{
m_size++;
m_current_ind++;
if (m_size > m_capacity)
{
extend();
}
m_stack_arr[m_current_ind] = u_value;
}
int32_t Stack::size() const
{
return m_size;
}
void Stack::extend()
{
int32_t* temp = new int32_t[m_capacity * 2];
m_capacity *= 2;
std::copy(m_stack_arr, m_stack_arr + m_size, temp);
delete[] m_stack_arr;
m_stack_arr = temp;
}
```