The output should look like this: the question is Design and implement the class
ID: 3678941 • Letter: T
Question
The output should look like this:
the question is
Design and implement the class myArray that solves the array index out of bounds problem and also allows user to begin the array index starting at any integer, positive or negative. Every object of type myArray is an array type of int. During execution, when accessing an array component; priate error message. Consider the following statements:
myArray list(5);
myArray myList(2,13);
myArray yourList(-5, 9);
the statement in line 1 declares list to be an array of 5 components, the component type is int, and the components are : list[0], list[1].......list[4]; the statement line 2 declares myList to be an array of 11 components, the component type is int, and the components are myList[2], myList[3] ......... myList[12]; the statement line 3 declares yourList to be an array of 14 components, the component type is int and the components are: yourList[-5], yourList[-4], ......... yourList[0], ..... youtList[8]. write a programto test the class myArray.
Explanation / Answer
#include <exception>
#include <sstream>
template<typename T>
class MyArray
{
public:
MyArray(int len) : len(len), data(new T[len]), start(0), end(len-1) { };
MyArray(int start, int end) : len(end - start + 1), start(start), end(end), data(new T[end - start + 1]) { };
~MyArray() { delete[] data; };
int size() const { return len; };
T const& operator[](int i) const { return data[check(i)]; };
T& operator[](int i) { return data[check(i)]; };
MyArray(const MyArray<T>&);
MyArray<T>& operator= (const MyArray<T>&);
private:
int len, start, end;
T* data;
int check(int i) const
{
if (i < start || i > end)
{
std::ostringstream o;
o << "Index " << i << " is out of bounds (" << start << ", " << end << ")";
throw std::out_of_range(o.str());
}
return start + i;
}
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.