C++ Iterating a huge std::multimap while handling many elements going MIA

206 Views Asked by At

I have a situation where objects will add events (a struct containing a function pointer to a function like object::do_something) to a "chain of events" (std::multimap) in their constructor. My interpreter reads the chain of events (sorted by depth) every time the game updates and executes each one sequentially. When an object is destroyed, it will remove all its events from the chain in its destructor automatically (to prevent possible leaks of events).

Because events are sorted by depth, it's possible that an object might register multiple events which are "next" to each other in the chain. When an object destroys itself, it unlinks all its events and immediately stops running its share of code (when something is destroyed, it can't do anything). I've cunningly produced a way of doing this; the particular function which deletes an object, instance_destroy() will throw an exception which my event interpreter can catch and continue along with the next event in the chain.

I've come to realize;

  • Unpredictable amounts of events can be unlinked from the chain, and the current iterator is (likely) to be invalidated when an object destroys itself.
  • Objects can destroy other objects in their lifetime, as well as themselves. I can't simply keep a copy of the next iterator that doesn't belong to the current object in case of destruction, as it could also be removed!

When control is passed back to the interpreter (say, via exception) and heaps of events have been removed, including possibly the current iterator, I have no way of knowing what to execute next. I can't start the map from the beginning -- that would cause undefined behaviour in the game; things would be executed twice. I also can't copy the map -- it's absolutely HUGE -- it would come at an enormous performance penalty. I can't redesign the way the system should work either, as it's not my protocol.

Consider the following data structure;

typedef std::multimap<real_t, event> events_by_depth_t;

How can I iterate it given my requirements above?

I'm using C++11.

0

There are 0 best solutions below