- //Matthew Fong
- //Lab 6: Templates
- //Description: using templates to create 2 arrays (ints and chars)
- #ifndef LAB6_H_INCLUDED
- #define LAB6_H_INCLUDED
- #include <iostream>
- using namespace std;
- template <class T> //Template class for the array types
- class myCollection
- {
- private:
- T *theArray;
- int size;
- public:
- myCollection(int i)
- {
- size = i; //Sets size to whatever i is
- }
- void set(T *array)
- {
- theArray = new T[size]; //Allocates memory
- for(int i = 0; i < size; i++)
- {
- theArray[i] = array[i]; //Copys the informatiom from array to theArray
- }
- }
- void print() //Prints out theArray
- {
- for (int i = 0; i < size; i++)
- {
- cout << theArray[i] << " ";
- }
- cout << endl;
- }
- ~myCollection() //Destructor that deletes theArray
- {
- delete [] theArray;
- }
- };
- #endif // LAB6_H_INCLUDED
- #include "lab6.h"
- #include <iostream>
- using namespace std;
- template <class T>
- void Min(T *array);
- int main()
- {
- myCollection<int> intArray(10); //Creates an object of int type
- myCollection<char> charArray(10); //Creates an object of char type
- int userint; //Input for the user's ints
- char userchar; //Input for the user's chars
- int *iArray; //Pointer to be used for set
- char *cArray; //Pointer to be used for set
- iArray = new int[10]; //Allocating memory
- cArray = new char[10]; //Allocating memory
- for(int i = 0; i < 10; i++) //For loop for setting the ints and letters to the arrays
- {
- cout << "Enter a number and a letter" << endl;
- cin >> userint >> userchar;
- iArray[i] = userint;
- cArray[i] = userchar;
- }
- intArray.set(iArray); //Sets the myCollection int array
- charArray.set(cArray); //Sets the myCollection char array
- intArray.print(); //Prints the int array
- charArray.print(); //Prints the char array
- Min<int> (iArray); //Calls the Min function for the int array
- Min<char> (cArray); //Calls the Min function for the char array
- delete [] iArray; //Deallocates the memory
- delete [] cArray; //Deallocates the memory
- return 0;
- }
- template <class T>
- void Min(T *array)
- {
- T lowest = array[0]; //Sets array to the first element of the array
- for(int i = 0; i < 10; i++)
- {
- if(lowest > array[i+1]) //If lowest is greater than the next element
- {
- lowest = array[i+1]; //Lowest becomes the next element
- }
- }
- cout << "The smallest element is : " << lowest << endl;
- }