首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何强制重组priority_queue?

如何强制重组priority_queue?
EN

Stack Overflow用户
提问于 2015-07-20 15:55:40
回答 1查看 334关注 0票数 2

我有一个priority_queue,它包含一个带有一些对象的vector

代码语言:javascript
复制
std::priority_queue<std::shared_ptr<Foo>, std::vector<std::shared_ptr<Foo>>, foo_less> foo_queue;

它有一个foo_queue函数,它将对priority_queue进行排序。

现在,在priority_queue之外,我希望更改一些必须影响priority_queue排序的对象值。

我的问题是:

我如何设置某种“刷新”来触发priority_queue来运行foo_queue(),以便始终保持它的有序性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-20 16:40:35

使用标准堆算法和向量创建自己的优先级队列。当您想要更改键时,从基础向量中查找并删除该值,并对该向量调用make_heap。更改密钥,然后将其推回堆中。因此,代价是对向量进行线性搜索以求值,并调用make_heap (我认为它也是线性的)。

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <algorithm>

template <class T, class Container = std::vector<T>,
          class Compare = std::less<T> >
class my_priority_queue {
protected:
    Container c;
    Compare comp;
public:
    explicit my_priority_queue(const Container& c_  = Container(),
                            const Compare& comp_ = Compare())
        : c(c_), comp(comp_)
    {
        std::make_heap(c.begin(), c.end(), comp);
    }
    bool empty()       const { return c.empty(); }
    std::size_t size() const { return c.size(); }
    const T& top()     const { return c.front(); }
    void push(const T& x)
    {
        c.push_back(x);
        std::push_heap(c.begin(), c.end(), comp);
    }
    void pop()
    {
        std::pop_heap(c.begin(), c.end(), comp);
        c.pop_back();
    }
    void remove(const T& x)
    {
        auto it = std::find(c.begin(), c.end(), x);
        if (it != c.end()) {
            c.erase(it);
            std::make_heap(c.begin(), c.end(), comp);
        }
    }
};

class Foo {
    int x_;
public:
    Foo(int x) : x_(x) {}
    bool operator<(const Foo& f) const { return x_ < f.x_; }
    bool operator==(const Foo& f) const { return x_ == f.x_; }
    int get() const { return x_; }
    void set(int x) { x_ = x; }
};

int main() {
    my_priority_queue<Foo> q;

    for (auto x: {7, 1, 9, 5}) q.push(Foo(x));
    while (!q.empty()) {
        std::cout << q.top().get() << '\n';
        q.pop();
    }

    std::cout << '\n';

    for (auto x: {7, 1, 9, 5}) q.push(Foo(x));
    Foo x = Foo(5);
    q.remove(x);
    x.set(8);
    q.push(x);
    while (!q.empty()) {
        std::cout << q.top().get() << '\n';
        q.pop();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31521028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档