view LightClone/Source/ArrayList.h @ 61:1fe27776627e

Added asserts
author koryspansel
date Mon, 03 Oct 2011 15:05:09 -0700
parents 95677f648a2c
children
line wrap: on
line source

/*
 * ArrayList
 */

#ifndef __ARRAYLIST_H__
#define __ARRAYLIST_H__

#include "Types.h"
#include "Debug.h"

/*
 * ArrayList
 */
template<typename Type>
class ArrayList
{
	/*
	 * pList
	 */
	Type* pList;

	/*
	 * nCapacity
	 */
	uint32 nCapacity;

	/*
	 * nSize
	 */
	uint32 nSize;

public:

	/*
	 * ArrayList
	 */
	ArrayList() : pList(0), nCapacity(0), nSize(0)
	{
	}

	/*
	 * ~ArrayList
	 */
	~ArrayList()
	{
		delete[] pList;
	}

	/*
	 * Add
	 */
	ErrorCode Add(Type kValue)
	{
		ErrorCode eCode = Resize(nSize + 1);
		if(eCode == Error_Success)
		{
			pList[nSize++] = kValue;
		}

		return eCode;
	}

	/*
	 * Remove
	 */
	ErrorCode Remove(uint32 nIndex)
	{
		ErrorCode eCode = Error_Fail;

		if(nIndex < nSize)
		{
			--nSize;

			for(uint32 i = nIndex; i < nSize; ++i)
			{
				pList[i] = pList[i + 1];
			}

			eCode = Error_Success;
		}

		return eCode;
	}

	/*
	 * Remove
	 */
	ErrorCode Remove(Type& kItem)
	{
		for(uint32 i = 0; i < nSize; ++i)
		{
			if(pList[i] == kItem)
			{
				--nSize;

				for(; i < nSize; ++i)
					pList[i] = pList[i + 1];

				return Error_Success;
			}
		}

		return Error_Fail;
	}

	/*
	 * Clear
	 */
	void Clear()
	{
		nSize = 0;
	}

	/*
	 * Size
	 */
	uint32 Size() const
	{
		return nSize;
	}

	/*
	 * Find
	 */
	int32 Find(Type& kValue) const
	{
		for(uint32 i = 0; i < nSize; ++i)
		{
			if(pList[i] == kValue)
			{
				return (int32)i;
			}
		}

		return -1;
	}

	/*
	 * operator []
	 */
	Type& operator[](uint32 nIndex)
	{
		ASSERT(nIndex < nSize);
		return pList[nIndex];
	}

	/*
	 * operator []
	 */
	const Type& operator[](uint32 nIndex) const
	{
		ASSERT(nIndex < nSize);
		return pList[nIndex];
	}

private:

	/*
	 * Resize
	 */
	ErrorCode Resize(uint32 nAmount)
	{
		if(nAmount > nCapacity)
		{
			Type* pArray = new Type[2 * nAmount];

			if(pList)
			{
				for(uint32 i = 0; i < nSize; ++i)
				{
					pArray[i] = pList[i];
				}

				delete[] pList;
			}

			pList		= pArray;
			nCapacity	= 2 * nAmount;
		}

		return Error_Success;
	}
};

#endif //__ARRAYLIST_H__