Smart Array Class - Overview

Platform: C++
Status: Released
Address: www.GeoffSamuel.com/Scrip_Files.php?proj=8


The Smart Array Class is a light weight generic dynamic array which gives developers the ability to create dynamically changing arrays with simple commands.

SmartArray .H File

///SMART TYPE ARRAY FOR HANDELING GENERIC DYNAMIC ARRAYS

//Generic Class
template <class T>

class SmartArray{
	//Private Vars
	int Lenght;			//The lenght of the array, used to extend the array
	T *Data;			//Pointer to the main array

public:
	SmartArray(){		//CONSTRUCTOR - Set the inital lenght and array through the Clear() Function
		Clear();
	}
	int Count(){		//Get the current size of the array, same as GetLenght()

		return Lenght;
	}
	int GetLenght(){	//Get the current size of the array, same as Count()
		return Lenght;
	}

	void Clear(){		//Clear the array and re-initilize the memory, called during the constructor
		Lenght = 0;
		Data = (T*)malloc(sizeof(T));
	}

	void RemoveAt(int index){	//function to remove a specific data entry

		if(index > Lenght){

			return;
		}else{
			if(Lenght == 0){
				Clear();
			}else{

				for(int i = index; i < Lenght; i++){

					Data[i] = Data[i+1];
				}
				Lenght--;
			}
		}
	}

	void InsertAt(const T &NewData,int index){	//function to instert a new element at a specific index


		if(index >= Lenght){
			Add(NewData);
		}else{

			Lenght++;
			Data = (T *) realloc(Data, (sizeof(T)*Lenght)*2);

			for(int i = Lenght-1; i > index; i--){

				Data[i] = Data[i-1];
			}
			Data[index] = NewData;
		}
	}

	void RemoveAt(int Start_index, int lenght_index){
		if(Start_index > Lenght){

			return;
		}else{
			if((Start_index == 0)&&(lenght_index >= Lenght)){

				Clear();
			}else{
				int remove_lenght = lenght_index;
				if(lenght_index + Start_index > Lenght){

					remove_lenght = (lenght_index + Start_index) - Lenght;
				}
				for(int i = Start_index; i < Lenght; i++){

					Data[i] = Data[i+remove_lenght];
				}
				Lenght -= remove_lenght;
			}
		}

	}

	void Add(const T &NewData){		//generic add new element to the end of the array
		Lenght++;

		Data = (T *) realloc(Data, (sizeof(T)*Lenght)*2);

		Data[Lenght-1] = NewData;

	}

	T& operator [] (int index)		//so the class can be used like an array

	{ 
		return Data[index]; // return array element  
	} 

	~SmartArray(){					//De-constructor, delete the variabls and free the memory

		delete Data;
		Lenght=NULL;
	}
};

Example of use

#include <IOStream>
#include "Smart_Arrays.h"		//Import the Smart_array header file

using namespace std;

int main(){

	SmartArray<int> DynIntArray;	//New Smart Array of type INT
	for(int i = 0; i < 3001; i++){	//Fill up the array with example data

		DynIntArray.Add(i);
	}
	for(int i = 0; i < DynIntArray.Count(); i++){	//loop through the array

		cout<<i<<":"<<DynIntArray[i]<<endl;			//pint the data
	}
	DynIntArray.Clear();			//Clear the array

	return 0;
}