Question

In: Computer Science

This is one lab question. I can not get this to work because of the templates,...

This is one lab question. I can not get this to work because of the templates, please help. It is extremely important the driver is not changed!!!!

Recall that in C++, there is no check on an array index out of bounds. However, during program execution, an array index out of bounds can cause serious problems. Also, in C++, the array index starts at 0.Design and implement the class myArray that solves the array index out of bounds problem and also allows the user to begin the array index starting at any integer, positive or negative.

Every object of type myArray is an array of type int. During execution, when accessing an array component, if the index is out of bounds, the program must terminate with an appropriate error message. Consider the following statements:
myArray list(5);                                   //Line 1
myArray myList(2, 13);                      //Line 2
myArray yourList(-5, 9);                     //Line 3

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 in Line 2 declares myList to be an array of 11 com- ponents, the component type is int, and the components are: myList[2], myList[3], ..., myList[12]; the statement in 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], ..., yourList[8].

  1. Add an overloaded operator!=(…) and operator==(…) functions.
  2. Use the attached driver to test the program (lab6_Driver.cpp):
   
#include <iostream> 
#include "myArray.h"

using namespace std;

int main()
{ 
    myArray<int> list1(5);
    myArray<int> list2(5);

    int i;

    cout << "list1 : ";
    for (i = 0 ; i < 5; i++)
        cout << list1[i] <<" ";
    cout<< endl;

    cout << "Enter 5 integers: ";
    for (i = 0 ; i < 5; i++)
        cin >> list1[i];
    cout << endl;

    cout << "After filling list1: ";

    for (i = 0 ; i < 5; i++)
        cout << list1[i] <<" ";
    cout<< endl;

    list2 = list1;
    cout << "list2 : ";
    for (i = 0 ; i < 5; i++)
        cout << list2[i] <<" ";
    cout<< endl;

    cout << "Enter 3 elements: ";

    for (i = 0; i < 3; i++)
        cin >> list1[i];
    cout << endl;

    cout << "First three elements of list1: ";
    for (i = 0; i < 3; i++)
        cout << list1[i] << " ";
    cout << endl;

    myArray<int> list3(-2, 6);

    cout << "list3: ";
    for (i = -2 ; i < 6; i++)
        cout << list3[i] <<" ";
    cout<< endl;

    list3[-2] = 7;
    list3[4] = 8;
    list3[0] = 54;
    list3[2] = list3[4] + list3[-2];

    cout << "list3: ";
    for (i = -2 ; i < 6; i++)
        cout << list3[i] <<" ";
    cout<< endl;

        if (list1 == list2)
                cout << " list 1 is equal to list2 " << endl;
        else
                cout << " list 1 is not equal to list2" << endl;

        if (list1 != list2)
                cout << " list 1 is not equal to list2 " << endl;
        else
                cout << " list 1 is equal to list2" << endl;

    system("pause");
    return 0;
}

So I need to write a myArray class that will work with this driver, that also overloads the operators. Do not change the driver. It must use a template <T>.

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

//myArray.h file

#ifndef myArray_H
#define myArray_H

#include <iostream>

using namespace std;

//myArray class
template <class T>
class myArray {
    //bounds
    int minIndex, maxIndex;
    //generic array pointer
    T* array;

public:
    //constructor taking capacity value
    myArray(int capacity);

    //constructor taking min and max index values, assuming min<max
    myArray(int min, int max);

    //destructor to deallocate array once done to prevent memory leaks
    ~myArray();

    //overloaded subscript operator
    T& operator[](int i);

    //overloaded equality checker
    bool operator==(const myArray<T>& other);

    //overloaded non equality checker
    bool operator!=(const myArray<T>& other);

    //overloaded assignment operator
    myArray<T>& operator=(const myArray<T>& other);
};

#endif
//myArray.cpp file

#include "myArray.h"

//implementation of all methods.

//constructor taking capacity value
template <class T>
myArray<T>::myArray(int capacity)
{
    //initializing array
    array = new T[capacity];
    //setting min and max indices appropriately
    minIndex = 0;
    maxIndex = capacity - 1;
    for (int i = minIndex; i <= maxIndex; i++) {
        array[i - minIndex] = T();
    }
}

//constructor taking min and max index values, assuming min<max
template <class T>
myArray<T>::myArray(int min, int max)
{
    //finding capacity from bounds
    int capacity = max - min;
    //initializing array
    array = new T[capacity];
    //setting bounds
    minIndex = min;
    maxIndex = max - 1;
    for (int i = minIndex; i <= maxIndex; i++) {
        array[i - minIndex] = T();
    }
}

//destructor to deallocate array once done to prevent memory leaks
template <class T>
myArray<T>::~myArray()
{
    delete[] array;
}

//overloaded subscript operator
template <class T>
T& myArray<T>::operator[](int i)
{
    //throwing an exception via a string value if index is invalid
    if (i < minIndex || i > maxIndex) {
        throw "Index out of bounds";
    }
    //otherwise returning value at i-minIndex
    return array[i - minIndex];
}

//overloaded == operator
template <class T>
bool myArray<T>::operator==(const myArray<T>& other)
{
        //checking if index bounds are equal
    if (minIndex == other.minIndex && maxIndex == other.maxIndex) {
        //looping and comparing values at each index
        for (int i = minIndex; i <= maxIndex; i++) {
            if (array[i - minIndex] != other.array[i - minIndex]) {
                //not same
                return false;
            }
        }
        return true; //same
    }
    return false; //different min/max indices
}
//overloaded != operator
template <class T>
bool myArray<T>::operator!=(const myArray<T>& other)
{
    return !(*this == other); //using previous method, negating result
}

//overloaded = operator
template <class T>
myArray<T>& myArray<T>::operator=(const myArray<T>& other)
{
    //deleting current array
    delete[] array;
    //initializing with new capacity
    array = new T[other.maxIndex - other.minIndex + 1];
    //setting min and max indices appropriately
    minIndex = other.minIndex;
    maxIndex = other.maxIndex;
    //copying values
    for (int i = minIndex; i <= maxIndex; i++) {
        array[i - minIndex] = other.array[i - minIndex];
    }
    //returning reference to new myArray
    return *this;
}

/*OUTPUT*/

list1 : 0 0 0 0 0
Enter 5 integers: 11 22 33 44 55

After filling list1: 11 22 33 44 55
list2 : 11 22 33 44 55
Enter 3 elements: 2 4 6

First three elements of list1: 2 4 6
list3: 0 0 0 0 0 0 0 0
list3: 7 0 54 0 15 0 8 0
 list 1 is not equal to list2
 list 1 is not equal to list2
Press any key to continue . . .

Related Solutions

CSI 1440 Lab 6 “Class Templates” Templates Templates in C++ is not a difficult idea. This...
CSI 1440 Lab 6 “Class Templates” Templates Templates in C++ is not a difficult idea. This lab is not intended to help you understand the details of how templates work. It is only intented to give students an opportunity to start developing code using templated classes. Everyone in the class has had to come to grips with the usage of variables in general. With templates, you can think of the type of the variable being a variable itself. The programmer...
This is one discussion question that I was hoping to get guidance on: What is the...
This is one discussion question that I was hoping to get guidance on: What is the correlation between, and evidence behind, market concentration and price levels? Do you find any relationship between lack of competition and other economic variables? What are the ethical ramifications of market concentration?
Can I get all of the question answered in a way that I know under which...
Can I get all of the question answered in a way that I know under which sub question the answer goes please. Can I get all of the questions answered in a way that I know how it fits in the question. Some parts are explanations. Thank you. Q. When a pink aqueous solution of potassium permanganate, faintly acidified with dilute sulfuric acid was treated with 10% aq. hydrogen peroxide, the reaction took place with the evolution of gas bubbles,...
HI , CAN I GET ANOTHE ANSWER BECAUSE THE ANSWER IS ALREADY TAKEN BY OTHER STUDEN...
HI , CAN I GET ANOTHE ANSWER BECAUSE THE ANSWER IS ALREADY TAKEN BY OTHER STUDEN IN MY CLASS,IS ABOUT MATERNITY CHILD NURSING CLASS THE QUESTION IS :How can electronic fetal monitoring inhibit the normal progress of labor? What can nurses do as advocates to counteract this effect?
Can I get the answers to these with work shown? 2, 3, 4, and 5 only...
Can I get the answers to these with work shown? 2, 3, 4, and 5 only please. 1. The following two linear functions represent a market (thus one is a supply function, the other a demand function). Circle the answer closest to being correct. Approximately what will the quantity demanded be if the government controls the market price to be $1.50 (You must first find the market equilibrium price and quantity in order to see how the $1.50 relates to...
   I put economics, because this question is from my econometrics review, I can change it...
   I put economics, because this question is from my econometrics review, I can change it to statistics if needed Question 1 Consider the following sample of 6 observations measuring students’ test scores (score) and average hours spent on studying each week (study).    Table 1 Score Study 95 18 85 11 93 15 80 7 100 16 89 10 Suppose that you are interested in estimating the following model:    score = β0 + β1study + u. (i) Use...
Can I get it solved step by step please with work shown You purchased a security...
Can I get it solved step by step please with work shown You purchased a security on 10/30/2018 at a price of $93.45. You redeemed the security on 03/27/ 2019 at a price of $99.75. Answer the following questions: Find APR Find EAR
I am very frustrated because I have submitted this question multiple times and no one has...
I am very frustrated because I have submitted this question multiple times and no one has been able to help, or fully help with the question. They have helped only with addressing the September portion when I have specifically asked for help with the October portion as well. Can anyone help me with the Sousa Realty Mini Practice Set from the College Accounting A Practical Approach 13th Edition textbook by Slater in Chapter 5? Please September 1, 201X: James Sousa...
Can I please get an in-depth answer to this question: You are an Audit Senior currently...
Can I please get an in-depth answer to this question: You are an Audit Senior currently planning the 30 June 20X9 audits of Comp Limited (Comp), Health Limited (Health), and News Limited (News). At recently scheduled planning meetings with Comp, Health and News, you obtain the following overview of this year’s operations for each of the three client companies: Comp is a manufacturer of computer hardware. The old costing system that was developed inhouse, could no longer keep up with...
a) the question is how can i get the weekly share price?? Collect the weekly share...
a) the question is how can i get the weekly share price?? Collect the weekly share price data(adjusted close) of these companies: - Humana Inc (HUM) - Lennar Corporation Class A (LEN) And collect the price data for the S&P500 market index for the period of one year. Calculate the weekly returns and graph the returns of the share prices and the index over the period(assume no dividends). Interpret the graph. Hint: Download data from Yahoo. Finance and do calculations...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT