高级优先级队列

时间:2012-10-18 17:18:43

标签: c++ data-structures filter set priority-queue

我正在寻找 C ++ 中优先级队列的实现。 除了STL 优先级队列中的基本功能外,还需要以下方法:

  1. 推送时可以删除所有相同的元素(由函数确定)(类似于集合)
  2. 它可以过滤掉一些元素(由另一个函数决定)。
  3. 您对如何实施它有什么建议吗?

2 个答案:

答案 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;
};