/********************************************************************** * array.h * A simple template-based array class. * * This class allows you to create an array of any type and size. It * is a simple demonstration of templates and how to use them in Unix. * * Support functions are provided to: * * o Return the size of the array. * * o Set an element of the array. * * o get the value of an element of the array. * * Unfortunately, no facility is provided to initialize an array. **********************************************************************/ #ifndef __ARRAY_H #define __ARRAY_H #include "assert.h" #include "stdlib.h" // Helpful for g++ in Unix. #pragma interface template class Array { private: T *data; // Pointer to the array. int size; // Size of the array. public: Array(int s); ~Array() { delete [] data; } int Set(const T val, int pos); int Get(T &val, int pos); int Size(void) { return size; } // Hopefully obvious. }; /********************************************************************** * Array::Array(int s) * * Create an array of type T of size s. Terminate if creation not * possible. **********************************************************************/ template Array::Array(int s) : size(s) { data = new T[s]; assert(data != NULL); } /********************************************************************** * Array::Set(const T val, int pos) * * Set the pos'th element of the array to val. * Return 1 if pos is valid, otherwise return 0. **********************************************************************/ template int Array::Set(const T val, int pos) { if (pos < 0 || pos >= size) return 0; data[pos] = val; return 1; } /********************************************************************** * Array::Get(const T val, int pos) * * Store the value of the pos'th element of the array in val. * Return 1 if pos is valid, otherwise return 0. **********************************************************************/ template int Array::Get(T &val, int pos) { if (pos < 0 || pos >= size) return 0; val = data[pos]; return 1; } #endif