The example of the creation of a dynamic array


Some useful functions to work with dynamic arrays are not realized in this program because it was written only to demonstrate the principle of creation such arrays.

The definition of the class:

template<class T>
class DynamicArray {
long size; //the size of the array
long count;
//the count of elements in the array
T* p; //the pionter to the beginning of the array

public:
//constructors
DynamicArray(long s = 10): size(s), count(0) {
p = new T[size];
}
DynamicArray(const DynamicArray& arr); //copying costructor
      //destructor
~DynamicArray() {
if(p) delete[] p;
}
      //functions-members
void add(T x);
void remove();
long length() const {return size;}
void print() const;

//operators
DynamicArray& operator=(const DynamicArray& arr); //assignment
T operator [] (long i) const; //indexing
DynamicArray& operator+(const DynamicArray& arr);
};

The implementation of functions and operators:

//copying costructor
template<class T>
DynamicArray<T>::DynamicArray(const DynamicArray& arr) {
size = arr.size;
count = arr.count;
p = new T[size];
for(int i = 0; i<count; ++i)
p[i] = arr.p[i];
}

This function returns a value by reference to permit a programmer to create a chain of assignments:

template<class T>
DynamicArray<T>&
DynamicArray<T>::operator=(const DynamicArray& arr)

if(this != &arr) { //to avoid assignments to itself
size = arr.size;

count = arr.count;
if(p) delete[] p;
p = new T[size];
for(int i = 0; i<count; ++i)
p[i] = arr.p[i];
     }
return *this;
}

template<class T>
T DynamicArray<T>::operator[](long i) const {
if(i < size && i)
return p[i-1];
else
return 0;
}

template<class T>
DynamicArray<T>&
DynamicArray<T>::operator+(const DynamicArray& arr) {
DynamicArray temp(*this); //store values in a temporary array
if(p) delete[] p;
size += arr.size;
count += arr.count;
p = new T[size];
for(int i = 0; i<temp.count; ++i)
p[i] = temp.p[i];
for(int i = 0; i<arr.count; ++i)
p[temp.count + i] = arr.p[i];
return *this;
}

template<class T>
void DynamicArray<T>::print() const {
cout<<"The array contains:"<<endl;
for(int i = 0; i<count; ++i)
cout<<p[i]<<' ';
cout<<endl;
}

template<class T>
void DynamicArray<T>::add(T x) {
if(count >= size) {
DynamicArray temp(*this);
if(p) delete[] p;
size += 10;
p = new T[size];
for(int i = 0; i<temp.count; ++i)
p[i] = temp.p[i];
}
p[count++] = x; //add the element to the end of the array
}

template<class T>
void DynamicArray<T>::remove() {
if(count)
p[--count] = 0; //delete the last element (if the array isn't
//empty
)
}

Download source files for this program

To the main page


Rambler's Top100
Хостинг от uCoz