I switched my code to use a regular list, and it's working alright.
But I guess I have a slightly different problem now: memory leaks.
I kinda figured when elements were removed from the list they weren't freed from memory, so I tried something like this:
if((*it)->food < 1)
{
for( auto leaf = (*it)->cells.begin(); leaf!=(*it)->cells.end(); ++leaf )
free(*leaf);
void *old = *it;
it = lifeforms.erase(it);
free(old);
}
I guess how this works depends on the actual class, so I'll post what I'm using right now:
class cell;
class lifeform
{
public:
list<cell*> cells;
int x,y;
int food;
int age;
int pointerX,pointerY;
int data[geneMaxLines][geneMaxArgs];
void doFunction(int a,int b,int c,int d,int e);
bool addCell(int newx,int newy,int newr,int newg,int newb);
};
list<lifeform*> lifeforms;
class cell
{
public:
int x,y;
bool alive;
int type;
int r,g,b;
int food;
Uint32 color;
lifeform *parent;
int eat();
void show();
};
This seems to cut down on the memory leaks, however I get a strage problem that the number of elements in the list is drastically differnet from the lists size, once the programs been running for a bit and many elements have been removed:
int cellCount = 0;
for( auto it = lifeforms.begin(); it!=lifeforms.end(); ++it )
cellCount++;
int difference = ((signed int)lifeforms.size())-cellCount;
Difference fluctuates rapidly, itll be in the thousands one frame and then tens the next.
Note that if I go back to just inserting the:
lifeforms.remove_if([](lifeform* n){ return n->food < 1; } );
the difference stops doing that.
Memory leaks occur with both methods, if I don't include free statements.