简体   繁体   English

优先队列排序指向更改值的对象的指针。 C ++

[英]Priority queue sorting pointers to objects that change value. C++

I have a queue that consists of pointers. 我有一个包含指针的队列。 It is sorted by node->p . 它按node->p排序。 Problem appears when I want to update priorities of elements inside the queue and then pop them in sorted order. 当我想更新队列中元素的优先级,然后按排序顺序弹出它们时,会出现问题。

#include <iostream>
#include <queue>

using namespace std;

struct node {
    int p;
    int d;
};

struct LessThanByP
{
    bool operator()(const node * lhs, const node * rhs) const
    {
        return lhs->p > rhs->p;
    }
};

int main(int argc, const char * argv[])
{
    priority_queue<node *, deque<node *>, LessThanByP> q;

    node *node1, *node3, *node2;
    node1 = new node;
    node2 = new node;
    node3 = new node;

    node1->p = 2;
    node2->p = 1;
    node3->p = 0;

    node1->d = 3;
    node2->d = 4;
    node3->d = 5;

    q.push(node3);
    q.push(node2);
    q.push(node1);

    node1->p = 1;
    node2->p = 2;
    node3->p = 3;

    while(!q.empty())
    {
        cout << q.top()->d << endl;
        q.pop();
    }

    return 0;
}

I am looking for a way to sort the queue after changing priorities of its elements. 我正在寻找一种在更改其元素的优先级后对队列进行排序的方法。

Result: 结果:

5
3
4

Expected result: 预期结果:

3
4
5

You cannot update the priority like that. 您不能像这样更新优先级。 The priority_queue assumes that objects do not suddenly change their value / order. priority_queue假定对象不会突然更改其值/顺序。 To update a value in the priority_queue you need to remove it from the queue, change it and then insert it again. 要更新priority_queue中的值,您需要将其从队列中删除,对其进行更改,然后再次将其插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM