问题描述
我想使用C ++ STL 容器适配器来实现计时器排队系统。
I want to implement a timer queuing system using the C++ STL priority_queue container adapter.
我的问题是,我想偶尔取消一个计时器,但没有接口,使我能够轻松地删除在priority_queue不是顶部项目的项目。
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.
有任何建议吗?
感谢您的协助。
推荐答案
我有一个完全相同的场景,并执行以下操作:
I had the exact same scenario once and did the following:
- 我保存在 std :: priority_queue 中的结构仅包含排序时间和 std的索引:: vector< Handler> (在我的情况下 Handler 是 boost :: function 但也可以是指向接口或函数的指针)
- 当添加一个计时器时,我会在处理程序的向量中找到一个空索引,处理程序。将索引和时间存储在priority_queue中。将索引返回给客户端作为令牌取消
- 取消计时器,传递添加时接收到的索引。清除该索引处的处理程序(对于 boost :: function 调用 clear(),如果使用指针,当它是回调定时器时,从优先级队列获得它的处理程序索引并检查处理程序向量 - 如果在那个位置的处理程序是空的()/ NULL,定时器已取消。将处理程序索引标记为自由。
- the structure I kept in 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)
- when adding a timer, I'd find a free index in the vector of handlers and store the handler at that index. Store the index and the time in the priority_queue. Return the index to the client as token to cancel
- to cancel a timer, pass the index received when adding it. Clear the handler at that index (for boost::function call clear(), if using pointers, set it to zero)
- when it's time to callback a timer, get its handler index from the priority queue and check the handlers vector - if the handler at that position is empty()/NULL, the timer has been canceled. Mark that handler index as free.
为了快速找到自由索引,我使用了一个单独的 std :: stack 的索引。当添加一个定时器并且栈是空的,在向量的末尾添加;
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.
这是将索引推送到自由索引堆栈的点。
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
这篇关于STL优先级队列 - 删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!