Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 93 lines (70 sloc) 1.65 KB
#ifndef com_sleepless_misc_array_cpp
#define com_sleepless_misc_array_cpp
// Copyright 1998-2004 Sleepless Software Inc. All Rights Reserved
#include <string.h>
/*
This object stores ptrs to whatever you want in a flat array.
You put ptrs in the array, and take them off by referencing the
array position with a positive integer. The indexing is 0-based.
If the array isn't long enough to accomodate the item
at the given index, the array will attempt to expand to the size
required to fit the item at the given index and fill the
in-between spaces with null pointers.
The internal capacity of the array does NOT shrink once it's expanded.
*/
class Array
{
private: void **list;
private: int len;
private: bool grow(int n)
{
int newLen = n;
void **newList = new void *[newLen];
if(!newList)
return false;
memset(newList, 0, sizeof(void *) * newLen);
if(list != NULL)
{
for(int i = 0; i < len; i++)
newList[i] = list[i];
delete list;
}
list = newList;
len = newLen;
return true;
}
public: Array()
{
list = NULL;
len = 0;
grow(10);
}
public: ~Array()
{
delete list;
}
// Places a pointer in the array at the location 'i'.
// Returns false, if it wasn't possible to grow the array to the
// needed size.
public: bool put(int i, void *p)
{
if(i < 0)
return false;
if(i >= len)
{
if(!grow(i + 1))
return false;
}
list[i] = p;
return true;
}
// Returns the pointer in the array at location 'i'.
// The pointer remains in the array unchanged.
public: void *get(int i)
{
if((i < 0) || (i >= len))
return NULL;
return list[i];
}
};
#endif // com_sleepless_misc_array_cpp