Wednesday 16 August 2017

Augment the safearay class in the ARROVER3 program in this chapter so that the user can specify both the upper and lower bound of the array (indexes running from 100 to 200, for example). Have the overloaded subscript operator check the index each time the array is accessed to ensure that it is not out of bounds. You’ll need to add a two argument constructor that specifies the upper and lower bounds. Since we have not yet learned how to allocate memory dynamically, the member data will still be an array that starts at 0 and runs up to 99, but perhaps you can map the indexes for the safearay into different indexes in the real int array. For example, if the client selects a range from 100 to 175, you could map this into the range from arr[0] to arr[75].


SOLUTION:
#include "stdafx.h"
#include "iostream"
using namespace std;
const int LIMIT = 100;
/////////////////////////////////////////////////////////////////////////////////////////
class safearay
{
            private:
                        int arr[LIMIT], u_limit, l_limit;
            public:
                        safearay(int l, int u) : l_limit(l), u_limit(u)         { }
                        int& operator [ ] (int n)             //note: return by reference
                        {
                                    l_limit -= (l_limit - 0);               u_limit -= (u_limit - 100);
                                    if( n < l_limit || n >= u_limit )
                                                {           cout << "\nIndex out of bounds\n";                 exit(1);             }
                                    return arr[n];
                        }
};
/////////////////////////////////////////////////////////////////////////////////////////
void main()
{
            int low, up, j;
            cout << "Enter Lower & Upper Limits of an Array of 100 Elements Respectively: ";
                        cin >> low >> up;
            safearay sa1(low,up);
            for(j = low; j < up; j++)
                        sa1[j-low] = (j-low)*10;
            for(j = low; j < up; j++)
                        {           int temp = sa1[j-low];               cout << "Element " << j << " is " << temp << endl;    }
            system("pause");
}
OUTPUT:

0 comments: