我正在寻找 C ++ 中优先级队列的实现。 除了STL 优先级队列中的基本功能外,还需要以下方法:
您对如何实施它有什么建议吗?
答案 0 :(得分:4)
您可以使用std::set
作为优先级队列而不重复。可以通过top
找到rbegin()
元素。渐近复杂度与二进制堆相同:O(1)top
符合rbegin
的标准要求,O(lg n )push
和O (lg n )pop
。但是,常数会更高。
对于过滤器,我建议你在一个带有自定义std::set
方法的类中包装push
(无论如何这是一个好主意),为你运行过滤谓词。
答案 1 :(得分:3)
只需打包priority_queue
:
#include <set>
#include <queue>
// Default predicate allows all objects through
template <typename T>
struct allow_any {
bool operator()(T const&) const {
return true;
}
};
// F is a callable type for the filtering predicate -- either a
// function pointer, or a class having an operator()(T const&).
template <typename T, typename F = allow_any<T> >
class filtering_priority_queue {
public:
explicit filtering_priority_queue(F f) : allow(f) {}
void push(T x) {
if (allow(x) && s.find(x) == s.end()) {
q.push(x);
s.insert(x);
}
}
T const& top() const {
return q.top();
}
void pop() {
s.erase(top());
q.pop();
}
private:
std::set<T> s;
std::priority_queue<T> q;
F allow;
};