I need a main function so I can test this code. Below is the cpp file for c++. #
ID: 3851850 • Letter: I
Question
I need a main function so I can test this code. Below is the cpp file for c++.
#include "ARRAY.h"
// Default constructor: Required for dynamic memory class
IntArray::IntArray()
{
size = 0;
data = nullptr; // NULL works in most compilers (not newer g++)
}
// Copy Constructor: Required for dynamic memory class
IntArray::IntArray(const IntArray& a)
{
size = 0;
data = nullptr;
*this = a; // Forces use of operator=
}
// Destructor: Required for dynamic memory class
IntArray::~IntArray()
{
// Clean up and delete array
if (data != nullptr)
{
delete[] data;
}
}
// Assignment op: Required for dynamic memory class
IntArray& IntArray::operator=(const IntArray& a)
{
// Check for self assignment (e.g., a = a)
if (this == &a)
{
// Always return *this
return *this;
}
// Create new chunk of memory (if needed)
int newSize = a.size;
int *newData;
if (newSize > 0)
{
newData = new int[newSize];
}
else
{
newData = nullptr;
}
// Copy all newSize elements over
for (int i = 0; i < newSize; ++i)
{
newData[i] = a.data[i];
}
// Delete old & copy over to this instance
if (data != nullptr)
{
delete[] data;
}
size = newSize;
data = newData;
// Always return *this
return *this;
}
// Add new value at end
void IntArray::append(int value)
{
// Create new chunk of memory
int newSize = size + 1;
int *newData = new int[newSize];
// Copy [We are copying the old size of elemens]
for (int i = 0; i < size; ++i)
{
newData[i] = data[i];
}
// Delete old & copy over to this instance
if (data != 0)
{
delete[] data;
}
size = newSize;
data = newData;
// Place new value
data[size - 1] = value;
}
// Access IntArray like an array: a[index] = i
int& IntArray::operator[](int index)
{
if (index >= 0 && index < size)
{
return data[index];
}
else
{
// We should throw an exception, but instead we'll just return -1
return -1;
}
}
// Access IntArray like an array: i = a[index]i
int IntArray::operator[](int index) const
{
if (index >= 0 && index < size)
{
return data[index];
}
else
{
// We should throw an exception, but instead we'll just return -1
return -1;
}
}
// Get size of array
int IntArray::getSize() const
{
return size;
}
// Remove
void IntArray::remove(int index)
{
for (int i = 0; i < size; i++)
{
data[i] = data[i + 1];
}
data[size - 1] = 0;
size = size - 1;
}
Explanation / Answer
int main()
{
IntArray arr;
for(int i=0;i<5;i++)
arr.append(i*2);
IntArray arr1;
for(int i=0;i<5;i++)
arr1.append(2+i);
arr=arr;
arr=arr1;
for(int i=0;i<arr.getSize();i++)
cout<<arr[i];
for(int i=0;i<arr.getSize();i++)
arr[i]=i*5;
arr[arr.getSize()-1]=3
for(int i=0;i<arr.getSize();i++)
cout<<arr[i];
}
Since you didn't provide the whole IntArray class I cannot compile and provide you with the output but I am pretty sure this would work.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.