In: Computer Science
Topic: Template
template
void arrayContents(const T *arr, int countSize);
int main()
{
const int ACOUNT = 5;
const int BCOUNT = 7;
const int CCOUNT = 6;
int a[ACOUNT] = {1, 2, 3, 4, 5};
double b[BCOUNT] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
char c[CCOUNT] = "HELLO";
cout <<"Array A contents: \n";
arrayContents(a, ACOUNT);
cout <<"Array B contents: \n";
arrayContents(b, BCOUNT);
cout <<"Array C contents: \n";
arrayContents(c, CCOUNT);
return 0;
}
template
void arrayContents(const T *arr, int countSize)
{
for(int i = 0; i < countSize; i++)
cout << arr[i] << " ";
cout << endl;
}
Rewrite the above code and overload function template
arrayContents(), so it will
takes two additional integer arguments, named int lowSubscript and
int
highSubscript. The function shall validate the lowSubscript
and
highSubscript; for:
If both either is out of range, or
If highSubscript is less than or equal to lowSubscript
hence,the overloaded arrayContents function should return 0.
Otherwise, it
should return the number of elements printed.
Modify the main() function to exercise each versions of
arrayContents on arrays
a, b and c.
Notes: the lowSubscript and highSubscript is to identify the index
of array.
Given below is the modified code as per specification. Please do
rate the answer if it helped. Thank you.
#include <iostream>
using namespace std;
template <typename T>
void arrayContents(const T *arr, int countSize);
template <typename T>
int arrayContents(const T *arr, int countSize, int lowSubscript,
int highSubscript);
int main()
{
const int ACOUNT = 5;
const int BCOUNT = 7;
const int CCOUNT = 6;
int a[ACOUNT] = {1, 2, 3, 4, 5};
double b[BCOUNT] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
char c[CCOUNT] = "HELLO";
cout <<"Array A contents: \n";
arrayContents(a, ACOUNT);
cout <<"Array B contents: \n";
arrayContents(b, BCOUNT);
cout <<"Array C contents: \n";
arrayContents(c, CCOUNT);
cout << endl << "----------" << endl;
cout <<"Array A contents between index 1 and 3: \n";
arrayContents(a, ACOUNT, 1, 3);
cout <<"Array B contents between index 3 and 6: \n";
arrayContents(b, BCOUNT, 3,6);
cout <<"Array C contents between index 0 and 2: \n";
arrayContents(c, CCOUNT, 0, 2);
return 0;
}
template <typename T>
void arrayContents(const T *arr, int countSize)
{
for(int i = 0; i < countSize; i++)
cout << arr[i] << " ";
cout << endl;
}
template <typename T>
int arrayContents(const T *arr, int countSize, int lowSubscript,
int highSubscript){
if(lowSubscript < 0 || highSubscript < 0 || highSubscript
< lowSubscript ||
lowSubscript >= countSize || highSubscript >=
countSize)
return 0;
int count = 0;
for(int i = lowSubscript; i <= highSubscript; i++){
cout << arr[i] << " ";
count++;
}
cout << endl;
return count;
}