如何更新 std::priority_queue 中的元素? [英] How to update elements inside an std::priority_queue?

查看:303
本文介绍了如何更新 std::priority_queue 中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <list>
#include <string.h>
#include <queue>
#include <algorithm>
#define pb push_back
using namespace std;
typedef pair<int,int> ii;


struct node{
    int digit;
};


class Compare{
public:
    bool operator()(node* a,node* b){
        return (a->digit)>(b->digit);
    }
};


int main()
{
priority_queue<node*,vector<node*>,Compare> pq;
vector<node*> vec;
node* p = new node();
node* q = new node();
node* r = new node();
p->digit=100;
q->digit=200;
r->digit=300;
pq.push(p);
pq.push(q);
pq.push(r);
q->digit=50;
pq.push(nod);
while(!pq.empty()){
    cout<<(pq.top())->digit<<endl;
    pq.pop();
}
return 0;
}

我创建了一个优先级队列并在优先级队列中插入了 3 个节点(结构),然后我更改了队列中存在的中间元素的值,但在更新元素后不知道如何更新优先级队列?

I created a priority queue and inserted 3 nodes(struct) in the priority queue and then I changed the value of the middle element present in the queue but cannot figure out how to update the priority queue after updating the element ?

推荐答案

优先级队列旨在以固定的优先级工作,即元素优先级在插入时应该知道,然后保持不变.这就是为什么所有的比较都是在元素被推入队列时完成的.

Priority queue is intended to work with fixed priorities, i.e. element priority should be known at the moment of insertion and then stay the same. That is why all the comparisons are done when the element is pushed into the queue.

如果您想要一个可以让您更改键的排序容器,请尝试 std::multimap.它将允许您删除任何元素并重新平衡自身.将它从 begin() 遍历到 end() 将按照所需的顺序访问您的 node.

If you want a sorted container that would let you change the keys, try std::multimap. It would allow you to remove any element and will rebalance itself. Traversing it from begin() to end() will visit your nodes in the desired order.

不幸的是,您仍然需要删除和插入元素来更改密钥,希望 C++17 能够对此做些什么.

Unfortunately you'll still have to remove and insert the element to change the key , hopefully C++17 will do something about it.

这篇关于如何更新 std::priority_queue 中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆