1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
#ifndef AnyList_H
#define AnyList_H
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
template <class T1, class T2>
class AnyList
{
private:
T1 *list; // Pointer to the array.
T1 numElements; // Number of elements.
T2 isValid(T1 ) const; // Validates subscripts.
public:
AnyList(T1 ); // Constructor
~AnyList(); // Destructor
T2 setNumElements(T1 );
T1 getNumElements() const { return numElements; }
void setElement(T1, T1); // Sets an element to a value
T1 getElement(T1 ) const; // Returns an element
};
template<class T1, class T2>
AnyList<T1, T2>::AnyList(int size)
{
list = new T1[size];
numElements = size;
for (int ndx = 0; ndx < size; ndx++)
list[ndx] = 0;
}
template<class T1, class T2>
AnyList<T1, T2>::~AnyList()
{
delete [] list;
}
template<class T1, class T2>
bool AnyList<T1, T2>::isValid(int element) const
{
T2 status;
if (element < 0 || element >= numElements)
status = false;
else
status = true;
return status;
}
template<class T1, class T2>
void AnyList<T1, T2>::setElement(int element, int value)
{
if (isValid(element))
list[element] = value;
else
if(setNumElements(element))
{
T1 *copyArray = new T1[element]; // allocate a new array on the heap
// copy the old array to the new allocated array
for(int i = 0; i < numElements; i++)
{
copyArray[i] = list[i];
}
// delete the array where 'list' was pointing to
delete [] list;
// set the other elements to 0
for(int j = numElements; j < element - 1; j++)
{
copyArray[j] = 0;
}
// set the last element to the 'value' passed to setNumbers
copyArray[element-1] = value;
// make 'list' point to the new, completed array
list = copyArray;
}
else
{
cout << "Error: Invalid subscript\n";
exit(EXIT_FAILURE);
}
}
template<class T1, class T2>
int AnyList<T1, T2>::getElement(int element) const
{
if (isValid(element))
return list[element];
else
{
cout << "Error: Invalid subscript\n";
exit(EXIT_FAILURE);
}
}
template <T1, T2>
bool AnyList<T1, T2>::setNumElements(int x)
{
if( x <= numElements )
return false;
else
{
return true;
}
}
#endif
|