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?
Asked
Active
Viewed 138 times
0

roalz
- 2,699
- 3
- 25
- 42

w4etwetewtwet
- 1,330
- 2
- 10
- 20
-
1If it stores events and functions, why not a map? For multiple functions, a multimap. – chris Jul 24 '13 at 08:47
-
@chris Thanks, sounds like what I want. I don't have much knowledge of what data structures are prebuilt into c++, so this is a great help! – w4etwetewtwet Jul 24 '13 at 08:51
-
@handuel, http://stackoverflow.com/a/471461/962089 – chris Jul 24 '13 at 08:52
-
@chris thanks once again. Bookmarked. – w4etwetewtwet Jul 24 '13 at 08:53
1 Answers
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
-
Thank you, fully answers the question, and thanks for showing me how to get all the event handlers. – w4etwetewtwet Jul 24 '13 at 09:21