简体   繁体   English

C ++,优先级队列,项目未排序

[英]C++, priority queue, items are not sorted

I have a problem with the priority queue: 我对优先级队列有疑问:

std::priority_queue <NodePrio, std::vector<NodePrio>, sortNodesByPrio> PQ;

where 哪里

struct NodePrio
{
Node *node;
double priority;

NodePrio() : node(NULL), priority(0) {}
NodePrio(Node *node_, double priority_) : node(node_), priority(priority_) {}
};

and

class sortNodesByPrio
{
public:
    bool operator () (const NodePrio &n1, const NodePrio  &n2)   const;
}


bool sortNodesByPrio::operator () (const NodePrio &n1, const NodePrio &n2) const
{
return n1.priority < n2.priority;
}

After repeatedly pushing new elements 在反复推动新元素之后

PQ.push(NodePrio(node, distance));

and from any point in time they are not sorted (see bellow)... I tried to debug the code, the comparator code has been repeatedly performed... 并且从任何时候开始,它们都没有被排序(请参见下面)...我试图调试代码,比较器代码已被重复执行...

Step1: 
push (node, 55.33);

PQ:
[0] 55.33

Step2:
push (node, 105.91);

PQ:
[0] 105.91
[1] 55.33

Step 3:
push (node, 45.18);

PQ:
[0] 105.91
[1] 55.33
[2] 45.18

Step 4:
push (node, 70.44);

PQ:
[0] 105.91
[1] 70.44
[2] 45.18
[3] 55.33   //Bad sort

Based on the "sample results" you show, it looks like you don't understand what a priority queue is. 根据显示的“样本结果”,您似乎不了解什么是优先级队列。

A priority queue guarantees that when you remove elements from it (using top() and pop() ), the elements will be removed in priority order. 优先级队列保证当您从中删除元素时(使用top()pop() ),这些元素将按优先级顺序被删除。 The elements are not stored in priority order, they are stored in a heap. 元素未按优先级顺序存储,而是存储在堆中。

You can consult your favorite algorithms book or website for more information on how a priority queue stores its elements. 您可以查阅自己喜欢的算法书籍或网站,以获取有关优先级队列如何存储其元素的更多信息。

Try changing 尝试改变

return n1.priority() < n2.priority();

to

return n1.priority < n2.priority;

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

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