Array class
Posted: Wed May 26, 2010 2:31 pm
I felt like sharing this, I just made a array class for my Engine and it's as close as I code get to stl vector. I did this to familiarise myself with templates and such. Feel free to make suggestions, or borrow ideas from it. I lost the file data from a power cut, but I managed to write it again in a couple of minutes so I think I got templates down
Code: Select all
/********************************************************
* Array.hpp
* GroundUpEngine
*
* Created by Hebron Sawyers
* Last Updated on 29/05/10
* Copyright 2009 by Hebron Sawyers. All rights reserved.
*
*********************************************************/
#ifndef __ARRAY_HPP
#define __ARRAY_HPP
namespace gue
{
template<class T>
class Array {
private:
/// Class Private Variables ///
T *Elements;
unsigned int Array_Size;
public:
/// De/Constructor ///
Array(unsigned int size = 0);
~Array();
/// Array Functions ///
unsigned int size();
void Resize(unsigned int size);
void push_back(T val);
void erase(unsigned int place);
void clear();
/// Array Operators ///
T& operator[](unsigned int place);
T* operator*();
};
/// ---------------------------------------- De/Constructor ---------------------------------------- ///
template<class T>
Array<T>::Array(unsigned int size)
{
Elements = new T[size];
Array_Size = size;
}
template<class T>
Array<T>::~Array()
{
delete[] Elements;
}
/// ---------------------------------------- Array Functions ---------------------------------------- ///
template<class T>
unsigned int Array<T>::size()
{
return Array_Size;
}
template<class T>
void Array<T>::Resize(unsigned int size)
{
T *temp = new T[size];
int min = 0;
if(size < Array_Size) min = size;
else min = Array_Size;
for(int i = 0; i < min; i++) {
temp[i] = Elements[i];
}
Array_Size = size;
delete[] Elements;
Elements = temp;
}
template<class T>
void Array<T>::push_back(T val)
{
Resize(Array_Size+1);
Elements[Array_Size-1] = val;
}
template<class T>
void Array<T>::erase(unsigned int place)
{
T *temp = new T[Array_Size-1];
unsigned int curr = 0;
for(unsigned int i = 0; i < Array_Size; i++) {
if(place != i+1) {
temp[curr] = Elements[i];
curr++;
}
}
Array_Size -= 1;
delete[] Elements;
Elements = temp;
}
template<class T>
void Array<T>::clear()
{
Array_Size = 0;
delete[] Elements;
}
/// ---------------------------------------- Array Operators ---------------------------------------- ///
template<class T>
T& Array<T>::operator[](unsigned int place)
{
return Elements[place];
}
template<class T>
T* Array<T>::operator*()
{
return Elements;
}
} // namespace gue
#endif // __ARRAY_HPP