Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-agent system in C++ code design

I have a simulation written in C++ in which I need to maintain a variable number of agents, and I am having trouble deciding how to implement it well. Every agent looks something similar to:

class Agent{
public:
    Vector2f pos;
    float health;
    float data[DATASIZE];
    vector<Rule> rules;
}

I need to maintain a variable number of agents in my simulation such that:

  1. Preferably, there is no upper bound on the number of agents
  2. I can easily add an Agent
  3. I can easily remove any agent under some condition (say health<0)
  4. I can easily iterate all agents and do something (say health--)
  5. Preferably, I can parallelize the work using openMP, because many updates are somewhat costly, but completely independent of other agents.
  6. (edit) the order of the agents doesn't matter at all

What kind of container or design principles should I use for the agents? Until now I was using a vector, but I think it pretty hard to erase from this structure: something I need to do quite often, as things die all the time. Are there any alternatives I should look at? I thought of something like List, but I don't think they can be parallelized because they are implemented as linked lists with iterator objects?

Thank you

like image 609
karpathy Avatar asked Feb 26 '23 08:02

karpathy


1 Answers

You could leave the agent in the list when dead, ready for re-use. No worries about shrinking your container, and you retain the benefits of a vector. You could keep a separate stack of pointers to dead/reusable agents, just push onto it when an agent dies, pop one off to reclaim for a new agent.

foreach Agent {
    if (agent.health > 0) // skip dead agents
        process rules
like image 102
Graham Perks Avatar answered Mar 02 '23 20:03

Graham Perks