I have a situation where I have a bunch of class objects whose member variables I need to update over time. The amount of objects I need to have can increase and decrease, and do so rapidly throughout my program's. Because I need to have a resizable array of class objects, I chose to use std::vector. Problem is, my current code crashes after about a minute or so of execution (I'm assuming memory leak or something, but I don't know for sure). Here's an example program I wrote to demonstrate what I am doing:
#include <Windows.h>
#include <iostream>
#include <vector>
char* names[] = {"Larry", "Bob", "xXx_Quicksc0p3zl33t_xXx", "InsertUnoriginalNameHere", "Idunno"};
class CEnt
{
public:
const char* name;
int health;
};
std::vector<CEnt> entities;
int main()
{
while (1)
{
int iEntCount = rand() % 1000 + 1; //Generate random value from 1000 to 2000. This simulates the changing ingame entity count that I grab
if (entities.size() != iEntCount)
{
entities.resize(iEntCount);
}
//Print.ToConsole(TYPE_NOTIFY, "%i", iEntCount);
for (int iIndex = 0; iIndex < iEntCount; iIndex++)
{
CEnt& Ent = entities[iIndex];
Ent.health = rand() % 100 + 1; //Generate random value to fill the objects. This simulates when I grab values from ingame entities and put them in each object
Ent.name = names[rand() % 5 + 1];
printf("Index: %i Name: %s Health: %i\n", iIndex, entities[iIndex].name, entities[iIndex].health);
}
}
}
It looks sloppy and it is, but it demonstrates what I am doing. Is there a better way to achieve this? I need to access a container at random points in my code that contains the last updated variables for each object in my vector.