Professional Documents
Culture Documents
Array
template <class T>
class LinearList {
public: LinearList(int MaxListSize = 10);
~LinearList() { delete [] element; }
bool isEmpty() { return length == 0; }
int Length() { return length; }
bool Find(int k, T& x);
int Search(const T& x);
LinearList<T>& Delete(int k, T& x);
LinearList<T>& Insert(int k, const T& x);
void Output(ostream& out);
private: int length;
int MaxSize;
T *element;
};
1
#include <iostream> //Template functions
using namespace std ;
//max returns the maximum of two elements
template <class T>
T max(T a, T b)
{ return a > b ? a : b ;
}
void main()
{ cout << "max(10, 15) = " << max(10, 15) << endl ;
cout << "max('k', 's') = " << max('k', 's') << endl;
cout << "max(10.1, 15.2) = " << max(10.1, 15.2)
<< endl ; } 2
template<class T>
void swapVariables(T& var1, T& var2)
{ T temp; //Template functions
temp = var1;
var1 = var2;
var2 = temp;
}
int main( )
{ float float1 = 3.5, float2 = 5.6;
swapVariables(float1, float2);
cout<<float1<<float2;
int int1=7, int2=3;
swapVariables(int1,int2);
Cout<<int1<<int2<<endl;
} 3
main()
Template functions {
int i, ii;
float x, xx;
double y, yy;
#include <iostream>
i = 2;
using namespace std; x = 2.2;
y = 2.2;
template <class T>
ii = square<int>(i);
T square(T x)
cout << i << ": " << ii << endl;
{
T result; xx = square<float>(x);
result = x * x; cout << x << ": " << xx << endl;
return result; // Explicit use of template
}; yy = square<double>(y);
cout << y << ": " << yy << endl;
5
Array--based Class ‘LinearList’
Array
template <class T>
class LinearList {
public: LinearList(int MaxListSize = 10);
~LinearList() { delete [] element; }
bool isEmpty() { return length == 0; }
int Length() { return length; }
bool Find(int k, T& x);
int Search(const T& x);
LinearList<T>& Delete(int k, T& x);
LinearList<T>& Insert(int k, const T& x);
void Output(ostream& out);
private: int length;
int MaxSize;
T *element;
};
6
Constructor ‘LinearList’
template<class T>
LinearList<T>::LinearList(int MaxListSize)
{ // Constructor for array-based linear list
MaxSize = MaxListSize;
element = new T[MaxSize];
length = 0;
}
7
Operation ‘Find’
template<class T>
bool LinearList<T>::Find(int k, T& x) const
{ // Set x to the k’th element in the list if it exists
if (k < 1 || k > length)
return false;
x = element[k-1];
return true;
}
12