如何在优先队列中找到价值?
我想在我的优先队列中找到一个节点,但我没有找到解决方案 :(如果你有解决方案,我很感兴趣.
I would like to find a node in my priority queue but I did not find a solution :( If you have a solution, I'm interested.
谢谢帮助.
推荐答案
如果你真的需要搜索一个 std::priority_queue
并且想要高效地完成它,你可以派生一个新类并添加find
成员函数.由于您没有添加任何其他状态,因此您不必担心切片或其他问题,因为 std::priority_queue
不是多态的.
If you really need to search through a std::priority_queue
and want to do it efficiently you can derive a new class and add a find
member function. Since you are not adding any additional state you do not have to worry about slicing or other issues since std::priority_queue
is not polymorphic.
#include <queue>
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class MyQueue : public std::priority_queue<T, Container, Compare>
{
public:
typedef typename
std::priority_queue<
T,
Container,
Compare>::container_type::const_iterator const_iterator;
const_iterator find(const T&val) const
{
auto first = this->c.cbegin();
auto last = this->c.cend();
while (first!=last) {
if (*first==val) return first;
++first;
}
return last;
}
};
相关文章