0

I am creating an input manager, that stored events, and associated methods (std::function<void()>) to call when an event occurs. However, there may be multiple events to call when an event was fired. The obvious way of storing the event - function paring would be a linked list, but as there may be multiple functions this won't work. I'm thinking of just having a linked list which stores arrays of std::function<void()> as the elements. Is this an appropriate method to use, and if not what is the safest approach?

roalz
  • 2,699
  • 3
  • 25
  • 42
w4etwetewtwet
  • 1,330
  • 2
  • 10
  • 20

1 Answers1

1

Store your mapping of Event->Function in a multimap, which can store key/value combinations with duplicate keys.

std::multimap<Event, std::function<void()>> events_;

When an event is fired, you can find a list of all event handlers using equal_range which returns a std::pair of iterators of all the event handling functions. Call each of these to handle the event, e.g. (untested code)

void on_event(Event const &e) {
  for (auto r = events_.equal_range(e); r.first != r.second; ++r.first)
    r.first->second();
}

equal_range returns a pair of iterators, so loop between the two. On each iteration of the loop the iterator (r.first) points to a key/value pair. r.first->first will be e and r.first->second will be the function handler.

cdmh
  • 3,294
  • 2
  • 26
  • 41