This one seems pretty stable... Maybe not, but looks like it
Code:
/*
Author: Cody Doughty
Data: March, 6, 2008
*/
#ifndef SMART_ARRAY_H
#define SMART_ARRAY_H
#include <cstdio>
#include <vector>
#include <list>
namespace Varia
{
template<class Type>
class XArray
{
public:
XArray(unsigned int p_iMax = 2000, bool p_bDebug = false):m_iMax(p_iMax),m_bDebug(p_bDebug),m_iSize(0)
{
if (m_bDebug)
{
printf("Creating XArray. Size = %d.\n", m_iMax);
printf("-->Estimated memory usage: %dbytes.\n", (sizeof(Type)*m_iMax));
}
m_vArray.resize(m_iMax);
std::vector<Type*>::iterator it;
for ( it = m_vArray.begin(); it != m_vArray.end(); ++it )
(*it) = NULL;
}
~XArray()
{
std::vector<Type*>::iterator it;
for ( it = m_vArray.begin(); it != m_vArray.end(); ++it )
if ( (*it) != NULL )
{
delete (*it);
}
}
void SetDebug(bool p_bDebug)
{
m_bDebug = p_bDebug;
}
int AddElement(Type* type)
{
if ( m_iSize >= m_iMax && m_vList.empty() )
{
return -1;
}
if ( !m_vList.empty() )
{
unsigned int index = m_vList.front();
if ( m_vArray.at(index) == NULL )
{
if ( m_bDebug )
printf("Setting Resource:%d\n",index);
m_vArray.at(index) = type;
m_vList.erase(m_vList.begin());
}
return index;
}
else
{
if ( m_bDebug )
printf("Setting Resource:%d\n",m_iSize);
m_vArray.at(m_iSize) = type;
++m_iSize;
return m_iSize-1;
}
}
int RemoveElement(unsigned int p_iIndex)
{
if ( p_iIndex <= m_iMax-1 )
{
if ( m_vArray.at(p_iIndex) != NULL )
{
if (m_bDebug)
printf("Removing element:%d\n",p_iIndex);
delete m_vArray.at(p_iIndex);
m_vArray.at(p_iIndex) = NULL;
m_vList.push_back(p_iIndex);
return p_iIndex;
}
else
{
return -1;
}
}
return -1;
}
void IncrementSize()
{
if ( m_iMax < m_vArray.max_size() )
{
if ( m_bDebug )
printf("Incrementing Array size from %d to %d.\n",m_iMax,m_iMax+1);
++m_iMax;
m_vArray.push_back(NULL);
m_vList.push_back(m_vArray.size()-1);
}
}
void DecrementSize()
{
if (!m_vArray.empty())
{
if ( m_bDebug )
printf("Decrementing Array size from %d to %d.\n",m_iMax,m_iMax-1);
if ( m_vArray.back() != NULL )
delete (m_vArray.back());
if ( m_iMax == m_iSize )
--m_iSize;
--m_iMax;
m_vArray.pop_back();
}
}
void Clear()
{
if ( m_bDebug )
printf("Clearing Array.\n");
std::vector<Type*>::iterator it;
for ( it = m_vArray.begin(); it != m_vArray.end(); ++it )
if ( (*it) != NULL )
{
delete (*it);
}
m_vArray.clear();
m_iMax = 0;
m_iSize = 0;
}
Type* GetElement(int p_iIndex)
{
if ( p_iIndex < m_iMax )
return m_vArray.at(p_iIndex);
}
private:
bool m_bDebug;
//
unsigned int m_iMax;
unsigned int m_iSize;
std::vector<Type*> m_vArray;
std::list<int> m_vList;
};
}
#endif //SMART_ARRAY_H