So, here is the header file where I implemented my own vector class in a simple way. The problem is that even though the code compiles, the member functions pushBack and insert both do not work properly.
I'd be really glad if anyone can figure out the problem in my code or find some ways how I can get this problem resolved.
#include <iostream>
#include <new>
using namespace std;
template <typename T>
class DiyVector
{
public:
DiyVector()
{
arr = new T[1];
arrSize = 0;
index = 0;
capacity = 1;
}
~DiyVector()
{
delete[] arr;
}
T& at(unsigned int index) const
{
if (index >= arrSize || index < 0)
{
throw OutOfRange{};
}
else
{
return arr[index];
}
}
unsigned int size() const
{
return arrSize;
}
void pushBack(const T& item)
{
if (arrSize == capacity)
{
arrTemp = new T[capacity += 1];
for (unsigned int i = 0; i < capacity; ++i)
{
arrTemp[i] = arr[i];
}
delete[] arr;
capacity++;
arr = arrTemp;
}
arr[arrSize] = item;
arrSize++;
}
void popBack()
{
if (arrSize == 0)
{
throw OutOfRange{};
}
else
{
arrSize--;
}
}
void erase(unsigned int index)
{
if (index >= arrSize || index < 0)
{
throw OutOfRange{};
}
else
{
arrTemp = new T[capacity -= 1];
for (unsigned int i = 0; i < capacity; ++i)
{
arrTemp[i] = arr[i];
}
delete[] arr;
capacity--;
arr = arrTemp;
}
}
void insert(unsigned int index, const T& item)
{
if (index >= arrSize || index < 0)
{
throw OutOfRange{};
}
else if (index == capacity)
{
pushBack(item);
}
else if (0 <= index && index <= size())
{
arr[index] = item;
}
}
class OutOfRange{};
private:
unsigned int arrSize;
unsigned int capacity;
unsigned int index;
T* arr;
T* arrTemp;
};