Answer to Question #214242 in Programming & Computer Science for Laraib

Question #214242

Write a class template that inputs the index of the array and displays the value in the specified index.


1
Expert's answer
2021-07-06T07:22:08-0400
#include <iostream>
#include <string>


using namespace std;




template <class T>
class Array
{
private:
	int length;
	T *data;
public:
	Array(int length,T *data)
	{
		if(length > 0){
			this->data = data;
			this->length = length;
		}
	}
	~Array(){
		
	}


	T& operator[](int index)
	{
		if(index >= 0 && index < length){
			return data[index];
		}
	}
};
int main () {
	int intNumbers[] = {10, 5, 8, 14, 12,32,85,47,66,12};
	Array<int> intArray(10,intNumbers);
	float floatNumbers[] = {12.6, 25.8, 36.35, 26.95, 11.41,85.12,39.62,85.12,47.95,15.74};
	Array<float> floatArray(10,floatNumbers);


	cout<<"Integer numbers:\n";
	for(int i=0;i<10;i++){
		cout<<intNumbers[i]<<" ";
	}
	cout<<"\nValue at index 5 = "<<intArray[5];
	cout<<"\nFloat numbers:\n";
	for(int i=0;i<10;i++){
		cout<<floatNumbers[i]<<" ";
	}
	cout<<"\nValue at index 8 = "<<floatArray[8]<<"\n\n";


	system("pause");
	return 0;
}






Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS