dynamic array for any object.
Posted: Fri Jul 24, 2009 9:28 am
this is not the best solution, has memory leaks and may not be fast. its just a quick and dirty solution.
Code: Select all
//main.cpp
#include "defs.h"
int main(int argc, char * const argv[])
{
cDynamicArray *list = new cDynamicArray(10);
for(int a = 0;a < 22;a++)
{
list->addItem(new cData(a+1));
}
list->printList();
list->printBounds();
return 0;
}
Code: Select all
//cDynamicArray.h/cpp
/*
* cDynamicArray.h
* binreadwrite
*
* Created by avansc on 7/24/09.
* Copyright 2009 BrOkEnBiT. All rights reserved.
*
*/
#include "defs.h"
#ifndef _cDynamicArray_h
#define _cDynamicArray_h
class cDynamicArray
{
public:
cDynamicArray(int size);
~cDynamicArray();
void addItem(cData *item);
cData *pGetItemAt(int index);
void grow();
void printList();
void printBounds();
private:
cData **ppArray;
int size;
int count;
};
#endif
/*
* cDynamicArray.cpp
* binreadwrite
*
* Created by avansc on 7/24/09.
* Copyright 2009 BrOkEnBiT. All rights reserved.
*
*/
#include "defs.h"
cDynamicArray::cDynamicArray(int size)
{
this->size = size;
this->count = 0;
this->ppArray = (cData**)malloc(sizeof(cData*)*size);
}
cDynamicArray::~cDynamicArray()
{
}
void cDynamicArray::addItem(cData *item)
{
this->ppArray[this->count] = item;
this->count++;
if(this->count == this->size)
{
this->grow();
}
}
cData *cDynamicArray::pGetItemAt(int index)
{
if(index >= count)
return NULL;
return this->ppArray[index];
}
void cDynamicArray::grow()
{
cData **TppArray = (cData**)malloc(sizeof(cData*)*this->size*2);
for(int a = 0;a < this->count;a++)
{
TppArray[a] = this->ppArray[a];
}
this->ppArray = TppArray;
this->size *=2;
}
void cDynamicArray::printList()
{
for(int a = 0;a < this->count;a++)
{
printf("%d\n", this->ppArray[a]->getNumber());
}
}
void cDynamicArray::printBounds()
{
printf("Array Size = %d\n", this->size);
printf("Index Size = %d\n", this->count);
}
Code: Select all
//cData.h/cpp
/*
* cData.h
* binreadwrite
*
* Created by avansc on 7/24/09.
* Copyright 2009 BrOkEnBiT. All rights reserved.
*
*/
#ifndef _cData_h
#define _cData_h
class cData
{
public:
cData(int number);
~cData();
void setNumber(int number);
int getNumber();
private:
int number;
};
#endif
/*
* cData.cpp
* binreadwrite
*
* Created by avansc on 7/24/09.
* Copyright 2009 BrOkEnBiT. All rights reserved.
*
*/
#include "defs.h"
cData::cData(int number)
{
this->number = number;
}
cData::~cData()
{
}
void cData::setNumber(int number)
{
this->number = number;
}
int cData::getNumber()
{
return this->number;
}