Hello
i need help with a program which allows the user random read access to any entry of the array. If the user attempts to read outside the useful region, your data structure should return a 0. Also It allows the user random write access to the useful region only. In case the user tries to write something in the part of the array that is supposed to be 0, print an error message.
this is the form of the array
[ 0 0 0 0 ... 0 0 1 2 3 4 5 0 0 .... 0 0 ]
i am not sure how to create Sparse Array, also i dont want to use existing libraries
this is what i have so far
#include <iostream>
using namespace std;
class MyArray {
friend ostream& operator <<(ostream &os, MyArray &array);
public:
MyArray(int size);
MyArray(const MyArray &rhs);
~MyArray();
MyArray& operator = (const MyArray& rhs);
int & operator[] (int index);
int read_element(int index);
void write_element(int index, int value);
private:
int *storage;
int size;
};
#include "sparse_array_1d.h"
MyArray::MyArray(int size)
{
storage = new int [size];
this -> size = size;
}
MyArray::MyArray(const MyArray &rhs)
{
size = rhs.size;
storage = new int[size];
(*this) = rhs;
}
MyArray::~MyArray()
{
delete [] storage;
}
int MyArray::read_element(int index)
{
return storage[index];
}
void MyArray::write_element(int index, int value)
{
storage[index] = value;
}
MyArray& MyArray::operator = (const MyArray &rhs)
{
int i,min_size;
if(size < rhs.size)
min_size = size;
else
min_size = rhs.size;
for(i=0; i<min_size; i++)
storage[i] = rhs.storage[i];
return (*this);
}
int & MyArray::operator[] (int index)
{
if(index < size && index >=0)
return storage[index];
return storage[0];
}
ostream & operator <<(ostream &os, MyArray &array)
{
int i;
os << "[ ";
for(i=0; i<array.size; i++)
os << array[i] << " ";
os << "]" << endl;
return os;
}
#include <iostream>
#include "myarray.h"
using namespace std;
void f(MyArray p, int size) //call-by-value, copy constructor should be called
// Note: what will change if we pass by by ref?
{
int i;
for(i=0 ; i<size; i++)
p[i] = 4*i;
cout << "p (in f)" << endl;
cout << p;
}
int main()
{
int i,size;
cout << "What array sizes would you like?" << endl;
cin >> size;
MyArray p1(size),p2(size),p3(size);
for(i=0 ; i<size; i++){
p1[i] = 2*i;
}
cout << "p1: " << endl;
cout << p1;
p3 = p2 = p1;
cout << "p2: " << endl;
cout << p2;
cout << "p3: " << endl;
cout << p3;
for(i=0 ; i<size; i++){
p2[i] = 3*i;
}
cout << "Check that deep copy was performed" << endl;
//Note: how will output be different if I had not
//overloaded = and used a shallow copy?
cout << "p1: " << endl;
cout << p1;
cout << "p2: " << endl;
cout << p2;
cout << "p3: " << endl;
cout << p3;
f(p1, size);
cout << "p1: " << endl;
cout << p1;
return 0;
}