I am trying to implement Dynamic Array using C++. However, my resize()
function seem to not work properly. There are no errors or warnings. I did some research and tried to look at other implementations found on the internet but was unable to fix the issue. I put my code below.
#include <iostream>
class Array
{
private:
int* arr;
int size = 0;
int capacity = 1;
public:
Array() { arr = new int[capacity]; }
Array(int capacity)
:
capacity(capacity)
{
arr = new int[capacity];
}
int length() const { return size; }
bool is_empty() const { return (length() == 0); }
int get(int index) const { return arr[index]; }
void set(int index, int value) { arr[index] = value; }
void resize()
{
capacity *= 2;
int* temp = new int[capacity];
for (int i = 0; i < size; i++) { temp[i] = arr[i]; }
delete[] arr;
arr = temp;
for (int i = 0; i < capacity; i++) { arr[i] = 0; }
}
void add(int value)
{
if (size + 1 >= capacity) { resize(); }
arr[size++] = value;
}
void remove(int index)
{
for (int i = index; i < size - 1; i++)
{
arr[i] = arr[i + 1];
}
size--;
}
int& operator[](int index)
{
return arr[index];
}
};
int main()
{
Array array;
for (int i = 0; i < 5; i++)
{
array.add(i + 1);
}
for (int i = 0; i < array.length(); i++)
{
std::cout << array.get(i) << " ";
}
std::cout << '\t' << array.length() << '\n';
return 0;
}
The code outputs:
0 0 0 4 5 5
But I expect it to output:
1 2 3 4 5 5
In your resize
method you copied over the existing elements from arr
for (int i = 0; i < size; i++) { temp[i] = arr[i]; }
But then later you 0
all of the elements out, effectively clearing the previous data
for (int i = 0; i < capacity; i++) { arr[i] = 0; }
Instead you likely just want to 0
the trailing new elements
for (int i = size; i < capacity; ++i) { arr[i] = 0; }