vendredi 15 avril 2022

Saving a varying-size 2D vector to a file

I'm making an evolutionary simulation. Every creature has a pair of (x, y) coordinates. I want to save them each simulation cycle. I need to save the data to a file since it takes up a lot of memory in the later stages of the simulation. The problem is that both the lifetime of the creature and the number of creatures are varying. Some may die off, new ones may be born. The number of cycles isn't fixed, the simulation runs until I stop it. My current code goes something like this:

Main simulation loop:

std::vector<std::shared_ptr<Creature>> creatures;
// ... Spawning the creatures

while (running)
{
    for (int i = 0; i < ConfigManager::Settings().numCreatures; i++)
    {
        creatures[i]->SimulateCycle();
    }

    // ... Code for handling the exit mechanism
}

Creature code:

void Creature::SimulateCycle()
{
    CalculatePosition();

    // Save data to file in binary
    file.write(reinterpret_cast<char*>(&posX), sizeof(posX));
    file.write(reinterpret_cast<char*>(&posY), sizeof(posY));
}

I'm currently just creating a new file for each creature, but that's not really feasible for a high number of creatures (2000+). What should I do?

P.S. As you can see, I don't literally have a "vector of vectors", I have a vector of Creatures and I save their position data to the corresponding file each cycle.

Aucun commentaire:

Enregistrer un commentaire