I want to implement a timer queuing system using the C++ STL priority_queue container adapter.
My problem is that I want to occasionally cancel a timer, however there are no interfaces that enable me to easily delete an item in the priority_queue that is not the top item.
Any suggestions?.
Thank you for your help.
I had the exact same scenario once and did the following:
std::priority_queue
contained only the time to sort by and an index to a std::vector<Handler>
(in my case Handler
was boost::function
, but could as well be pointer to interface or function)boost::function
call clear()
, if using pointers, set it to zero)1 To make finding a free index fast, I used a separate std::stack
of indices. When adding a timer and that stack is empty, add at the end of vector; otherwise pop the top index and use it.
2 Here's the point when you push the index to the free indices stack
The whole thing is somewhat tricky and error-prone, especially if your timer callbacks need to add or cancel timers. Here's a link to my canceling timer class described above, this code is public domain