I am currently taking a data structures class and I've run into a snag regarding one of the projects. It's a big one, as every other project after it requires it.
Class templates.
I get the general idea, but whenever I try to implement it, something or another goes horribly wrong. I've been at it for a while now, and I've all but given up on it. Can anyone show me how to (in my professor's own words, typos and all):
Include the template class implementation <class T> and replace int in the above class whenever required for T (warning due not change int for T whenever is not required).
This is as far as I got.
Code:
------------------array.h------------------
template <typename T>
class Array
{
public:
Array<T> (int numelems)
{
Alist = new T[numelems];
nume = numelems;
for (int i=0; i<nume; i++)
Alist[i]=0;
top = -1;
}
bool operator > (T a)
{
if (++top < nume)
Alist[top]=a;
if ((top+1) < nume)
return true;
else return false;
}
void displayArray();
void Sort();
~Array();
private:
T* Alist;
int top;
int nume;
};
------------------array.cpp------------------
#include <iostream>
#include "array.h"
template <typename T>
void Array<T>::displayArray()
{
for (int i=0; i<nume; i++)
std::cout << Alist[i] << std::endl;
}
template <typename T>
void Array<T>::Sort()
{
T temp;
int check;
check=1;
while (check!=0)
{
check=0;
for (int i=0; i<(nume-1); i++)
{
if (Alist[i] > Alist[i+1])
{
check=1;
temp=Alist[i];
Alist[i]=Alist[i+1];
Alist[i+1]=temp;
}
}
}
return;
}
template <typename T>
Array<T>::~Array()
{
delete [] Alist;
}
------------------usingarray.cpp------------------
#include <iostream>
#include "array.h"
using namespace std;
int main()
{
int x, i;
cout << "Input size of the int array: ";
cin >> i;
Array<int> A_int(i);
cout << "Input elements into the int array: " << endl;
do {
cin >> x;
} while (A_int > x);
cout << "The array is full." << endl << endl;
A_int.Sort();
cout << "The sorted int array" << endl;
A_int.displayArray();
cout << endl;
return 0;
}