Untitled

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
2.4 kB
3
Indexable
Never
#include <iostream>

using namespace std;

template <class T>
class Array {
public:
	Array(int size) {
		if (size < 1)
			cout << "Errore nel costruttore!" << endl;
		else {
			this->size = size;
			elements = new T[size];
			this->index = 0;
			this->usedElements = 0;
		}
	}
	~Array() {
		delete[] elements;
	}
	void add(T value) {
		if (usedElements < size) {
			elements[index] = value;
			index++;
			usedElements += 1;
		}
		else {
			T* tmpElements;
			tmpElements = new T[size];
			for (int i = 0; i < (size); i++)
				tmpElements[i] = elements[i];
			delete[] elements;
			size += 1;
			elements = new T[size];
			for (int i = 0; i < size; i++) {
				elements[i] = tmpElements[i];
				if (i == (size - 1))
					elements[i] = value;
			}
			delete[] tmpElements;
			usedElements += 1;
			size = usedElements;
		}
	}
	int getUsedElements() {
		return this->usedElements;
	}
	T getElements(int index) {
		return elements[index];
	}
	void findMax() {
		T max = elements[0];
		for (int i = 0; i < usedElements; i++) {
			if (elements[i] > max)
				max = elements[i];
		}
		if (max != elements[0])
			cout << "Valore massimo = " << max << endl;
	}
private:
	T* elements;
	int size;
	int index;
	int usedElements;
};

template<class T>
inline ostream& operator << (ostream& out, Array<T>& istance) {
	for (int i = 0; i < istance.getUsedElements(); i++)
		out << istance.getElements(i) << " ";
	return out;
}


int main() {
	Array<int> firstInstanceVectorTemplateClass(1);
	Array<float> secondInstanceVectorTemplateClass(1);
	Array<char> thirdInstanceVectorTemplateClass(1);
	firstInstanceVectorTemplateClass.add(2);
	firstInstanceVectorTemplateClass.add(3);
	firstInstanceVectorTemplateClass.add(4);
	secondInstanceVectorTemplateClass.add(2.5);
	secondInstanceVectorTemplateClass.add(39.1);
	secondInstanceVectorTemplateClass.add(0.6);
	thirdInstanceVectorTemplateClass.add('a');
	thirdInstanceVectorTemplateClass.add('b');
	thirdInstanceVectorTemplateClass.add('c');
	cout << firstInstanceVectorTemplateClass << endl;
	cout << secondInstanceVectorTemplateClass << endl;
	cout << thirdInstanceVectorTemplateClass << endl;
	firstInstanceVectorTemplateClass.findMax();
	secondInstanceVectorTemplateClass.findMax();
	thirdInstanceVectorTemplateClass.findMax();
}